From 8c4058d122e2936a8c9955872af1e0dd694497e3 Mon Sep 17 00:00:00 2001 From: Tony Tkacik Date: Wed, 26 Feb 2020 11:42:33 +0100 Subject: [PATCH 01/55] debugDump: remove unnecessary overrides of default method --- .../icf/dummy/resource/DummyAccount.java | 5 ----- .../evolveum/icf/dummy/resource/DummyGroup.java | 5 ----- .../icf/dummy/resource/DummyResource.java | 6 ------ ...ompositeRefinedObjectClassDefinitionImpl.java | 5 ----- .../common/refinery/PropertyLimitations.java | 5 ----- .../RefinedObjectClassDefinitionImpl.java | 4 ---- .../prism/delta/PartiallyResolvedDelta.java | 5 ----- .../midpoint/prism/query/ValueFilter.java | 16 ---------------- .../prism/xml/ns/_public/query_3/QueryType.java | 5 ----- .../xml/ns/_public/query_3/SearchFilterType.java | 5 ----- .../prism/impl/delta/DeltaMapTripleImpl.java | 8 -------- .../prism/impl/delta/DeltaSetTripleImpl.java | 8 -------- .../prism/impl/delta/ObjectDeltaImpl.java | 5 ----- .../midpoint/prism/impl/query/AllFilterImpl.java | 5 ----- .../prism/impl/query/ExistsFilterImpl.java | 5 ----- .../prism/impl/query/ObjectPagingImpl.java | 5 ----- .../prism/impl/query/ObjectQueryImpl.java | 5 ----- .../prism/impl/query/ValueFilterImpl.java | 5 ----- .../prism/impl/schema/SchemaRegistryImpl.java | 5 ----- .../xml/GlobalDynamicNamespacePrefixMapper.java | 5 ----- .../midpoint/prism/impl/xnode/XNodeImpl.java | 5 ----- .../midpoint/schema/ObjectTreeDeltas.java | 5 ----- .../statistics/ConnectorOperationalStatus.java | 5 ----- .../com/evolveum/midpoint/test/util/Lsof.java | 5 ----- .../midpoint/model/api/ProgressInformation.java | 5 ----- .../midpoint/model/api/util/MergeDeltas.java | 5 ----- .../model/impl/lens/ConstructionPack.java | 5 ----- .../model/impl/lens/ObjectDeltaWaves.java | 5 ----- .../model/impl/scripting/PipelineData.java | 5 ----- .../impl/sync/ReconciliationTaskResult.java | 5 ----- .../visualizer/output/SceneDeltaItemImpl.java | 5 ----- .../model/impl/visualizer/output/SceneImpl.java | 5 ----- .../impl/visualizer/output/SceneItemImpl.java | 5 ----- .../model/impl/util/mock/MockClockworkHook.java | 8 -------- .../midpoint/model/test/DummyTransport.java | 5 ----- .../notifications/api/transports/Message.java | 5 ----- .../wf/impl/processors/StartInstruction.java | 5 ----- .../api/ResourceEventDescription.java | 8 -------- .../ResourceObjectShadowChangeDescription.java | 8 -------- .../api/ResourceOperationDescription.java | 8 -------- .../midpoint/provisioning/ucf/api/Change.java | 5 ----- .../midpoint/audit/api/AuditEventRecord.java | 6 ------ .../repo/sql/query/definition/Definition.java | 5 ----- .../sql/query2/QueryDefinitionRegistry2.java | 5 ----- .../query2/definition/JpaDataNodeDefinition.java | 5 ----- .../query2/definition/JpaEntityDefinition.java | 5 ----- .../sql/query2/definition/JpaLinkDefinition.java | 5 ----- .../sql/query2/resolution/HqlDataInstance.java | 5 ----- .../resolution/ItemPathResolutionState.java | 5 ----- .../midpoint/test/DummyAuditService.java | 5 ----- 50 files changed, 280 deletions(-) diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java index 3b350c164a5..6db0cfc1ab0 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyAccount.java @@ -72,11 +72,6 @@ public String toStringContent() { return super.toStringContent() + ", password=" + password; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override protected void extendDebugDump(StringBuilder sb, int indent) { sb.append("\n"); diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java index ecc53817ddc..c838b5b8851 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyGroup.java @@ -68,11 +68,6 @@ public String toStringContent() { return super.toStringContent() + ", members=" + getMembers(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override protected void extendDebugDump(StringBuilder sb, int indent) { sb.append("\n"); diff --git a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java index 16b69863536..b151a88b9ed 100644 --- a/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java +++ b/icf-connectors/dummy-resource/src/main/java/com/evolveum/icf/dummy/resource/DummyResource.java @@ -1075,12 +1075,6 @@ private void traceOperation(String opName, long counter) { } } - - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(toString()); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java index 293d6579418..c77ecaf6904 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/CompositeRefinedObjectClassDefinitionImpl.java @@ -715,11 +715,6 @@ public boolean equals(Object obj) { return true; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { return debugDump(indent, (LayerType) null); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java index a792a746e2f..fe6753bdb44 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/PropertyLimitations.java @@ -57,11 +57,6 @@ public void setAccess(PropertyAccessType access) { this.access = access; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java index c32ce9ecde6..bc2d499f90b 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/refinery/RefinedObjectClassDefinitionImpl.java @@ -1183,10 +1183,6 @@ private void add(RefinedAttributeDefinition refinedAttributeDefinition) { //endregion //region Diagnostic output, hashCode/equals ========================================================= - @Override - public String debugDump() { - return debugDump(0); - } @Override public String debugDump(int indent) { diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java index a61fb016497..8a5c3ae5a3f 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/delta/PartiallyResolvedDelta.java @@ -58,11 +58,6 @@ public int hashCode() { return Objects.hash(delta, residualPath); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java index c002c5fa7f2..ea353ebb5f9 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/query/ValueFilter.java @@ -97,25 +97,9 @@ public interface ValueFilter ext @Override ValueFilter clone(); - @SuppressWarnings("EqualsWhichDoesntCheckParameterClass") - @Override - boolean equals(Object o); - @Override boolean equals(Object o, boolean exact); - @Override - int hashCode(); - - @Override - String debugDump(); - - @Override - String debugDump(int indent); - - @Override - String toString(); - //String getFilterName(); //void debugDump(int indent, StringBuilder sb); diff --git a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java index aa32ef7baa7..b226014a81d 100644 --- a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java +++ b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/QueryType.java @@ -612,11 +612,6 @@ public QueryType clone() { } } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java index 3d574221c23..4f8d402866e 100644 --- a/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java +++ b/infra/prism-api/src/main/java/com/evolveum/prism/xml/ns/_public/query_3/SearchFilterType.java @@ -267,11 +267,6 @@ public SearchFilterType clone() { return clone; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java index fce69617d79..7351733491c 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaMapTripleImpl.java @@ -261,14 +261,6 @@ private void dumpMap(StringBuilder sb, String label, Map set) { sb.append(label).append(": ").append(set).append("; "); } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java index 106446f6929..0499804c23f 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/DeltaSetTripleImpl.java @@ -387,14 +387,6 @@ private void dumpSet(StringBuilder sb, String label, Collection set) { sb.append(label).append(": ").append(set).append("; "); } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java index ebece72f933..d477d01f090 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/delta/ObjectDeltaImpl.java @@ -1029,11 +1029,6 @@ public String toDebugType() { return objectTypeClass.getSimpleName(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java index 95d443ed592..c23fda880cf 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/AllFilterImpl.java @@ -40,11 +40,6 @@ public void checkConsistence(boolean requireDefinitions) { // nothing to do } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java index e2b28435ef5..af50cee7b6f 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ExistsFilterImpl.java @@ -112,11 +112,6 @@ public void checkConsistence(boolean requireDefinitions) { } } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java index 6296e292341..b43d42d08a4 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectPagingImpl.java @@ -284,11 +284,6 @@ private void copyTo(ObjectPagingImpl clone) { clone.cookie = this.cookie; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java index 5e38b2823d8..a3c0765f6a2 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ObjectQueryImpl.java @@ -93,11 +93,6 @@ public ObjectQueryImpl cloneEmpty() { return clone; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java index 90bdd14edaa..80e865fdbee 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/query/ValueFilterImpl.java @@ -315,11 +315,6 @@ public int hashCode() { return Objects.hash(fullPath, matchingRule, values, expression, rightHandSidePath); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java index f81f90ea44a..8c1df3958e9 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/schema/SchemaRegistryImpl.java @@ -598,11 +598,6 @@ public Collection getCompileTimePackages() { } //endregion - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java index 3e3c95e41de..4344155df43 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xml/GlobalDynamicNamespacePrefixMapper.java @@ -182,11 +182,6 @@ private Map clonePrefixMap(Map map) { return clone; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java index bfc9b8af9a0..cfcc66215c7 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/xnode/XNodeImpl.java @@ -198,11 +198,6 @@ protected void copyCommonAttributesFrom(XNodeImpl xnode) { setMaxOccurs(xnode.getMaxOccurs()); } - @Override - public String debugDump() { - return debugDump(0); - } - public abstract String getDesc(); protected String dumpSuffix() { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java index 906b7623f95..d59db482db1 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/ObjectTreeDeltas.java @@ -197,11 +197,6 @@ public String toString() { '}'; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java index d82efb8b450..2073d146173 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/statistics/ConnectorOperationalStatus.java @@ -224,11 +224,6 @@ public String toString() { return "ConnectorOperationalStatus(" + connectorName + ": " + connectorClassName + ": " + poolStatusNumActive + "/" + poolConfigMaxSize+")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java index a5165be2a5d..5b4a64d7c04 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/Lsof.java @@ -280,11 +280,6 @@ private void diff(StringBuilder sb, String key, Integer baselineValue, Integer c sb.append("\n"); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java index 6f0fecfea74..9d08dbe77f8 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ProgressInformation.java @@ -120,11 +120,6 @@ public void setMessage(String message) { this.message = message; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java index 2d2f779bf7e..511bff5f854 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/util/MergeDeltas.java @@ -96,11 +96,6 @@ public String toString() { + ", rightLinkDelta=" + rightLinkDelta + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java index 0e8139158bf..98ab05fbef4 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ConstructionPack.java @@ -62,11 +62,6 @@ public String toString() { return "ConstructionPack(" + SchemaDebugUtil.prettyPrint(constructions) + (forceRecon ? ", forceRecon" : "") + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java index 49adbf6a7ba..a3ef1ebdfd0 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ObjectDeltaWaves.java @@ -320,11 +320,6 @@ public List> subList(int fromIndex, int toIndex) { // DUMP - @Override - public String debugDump() { - return debugDump(0); - } - public String dump(boolean showTriples) { return debugDump(0, showTriples); } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java index 0be0a7889c9..bdc692dfb22 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/PipelineData.java @@ -52,11 +52,6 @@ public List getData() { return data; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { return DebugUtil.debugDump(data, indent); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java index ac1914165e8..2497e61209f 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/ReconciliationTaskResult.java @@ -148,9 +148,4 @@ public String debugDump(int indent) { return sb.toString(); } - @Override - public String debugDump() { - return debugDump(0); - } - } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java index 6d29ec26e94..8a4858b71c8 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneDeltaItemImpl.java @@ -79,11 +79,6 @@ public void setSourceDelta(ItemDelta sourceDelta) { this.sourceDelta = sourceDelta; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = debugDumpCommon(indent); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java index 1ff40549e8f..86c6fdfbd3a 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneImpl.java @@ -139,11 +139,6 @@ public void setSourceDelta(ObjectDelta sourceDelta) { this.sourceDelta = sourceDelta; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java index 35ca4cd3f33..6e79eac651e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/visualizer/output/SceneItemImpl.java @@ -86,11 +86,6 @@ public void setSourceRelPath(ItemPath sourceRelPath) { this.sourceRelPath = sourceRelPath; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = debugDumpCommon(indent); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java index e6a723ec621..3681fe99884 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/util/mock/MockClockworkHook.java @@ -105,14 +105,6 @@ public void invokeOnException(@NotNull ModelContext context, @NotNull Throwable // // } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java index 5dcc5ea2f9e..844c2e693bf 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/DummyTransport.java @@ -93,11 +93,6 @@ public String getName() { return "dummy"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java index f28b7430d5e..42d4b51a57f 100644 --- a/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java +++ b/model/notifications-api/src/main/java/com/evolveum/midpoint/notifications/api/transports/Message.java @@ -154,11 +154,6 @@ public String toString() { return sb.toString(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder rv = new StringBuilder(); diff --git a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java index 292490644e9..b7860937bb4 100644 --- a/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java +++ b/model/workflow-impl/src/main/java/com/evolveum/midpoint/wf/impl/processors/StartInstruction.java @@ -148,11 +148,6 @@ public String toString() { '}'; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java index 2b7a62476aa..0384546e40c 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceEventDescription.java @@ -77,14 +77,6 @@ public String toString() { + ")"; } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java index f022a30eae7..aeecae5d4c2 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceObjectShadowChangeDescription.java @@ -165,14 +165,6 @@ public String toString() { + ", resource=" + resource + (unrelatedChange ? " UNRELATED" : "") + (simulate ? " SIMULATE" : "") + (cleanDeadShadow ? " CLEAN DEAD SHADOW" : "") + ")"; } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java index 2fc68a04e73..9847705d877 100644 --- a/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java +++ b/provisioning/provisioning-api/src/main/java/com/evolveum/midpoint/provisioning/api/ResourceOperationDescription.java @@ -145,14 +145,6 @@ public String toString() { ", result=" + result + ")"; } - /* (non-Javadoc) - * @see com.evolveum.midpoint.util.DebugDumpable#debugDump() - */ - @Override - public String debugDump() { - return debugDump(0); - } - /* (non-Javadoc) * @see com.evolveum.midpoint.util.DebugDumpable#debugDump(int) */ diff --git a/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java b/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java index 0604ec6ef91..adfeda3f929 100644 --- a/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java +++ b/provisioning/ucf-api/src/main/java/com/evolveum/midpoint/provisioning/ucf/api/Change.java @@ -163,11 +163,6 @@ public String toString() { + ", oldRepoShadow=" + oldRepoShadow + ", currentResourceObject=" + currentResourceObject + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java b/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java index 4106169c928..414b6f3d3b2 100644 --- a/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java +++ b/repo/audit-api/src/main/java/com/evolveum/midpoint/audit/api/AuditEventRecord.java @@ -640,12 +640,6 @@ private String formatReference(PrismReferenceValue refVal) { return refVal.toString(); } - - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java index 05a8eabf0c8..ec78f72b463 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query/definition/Definition.java @@ -82,11 +82,6 @@ protected String dumpQName(QName qname) { return builder.toString(); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java index 231cc2e54f7..b933cbd05b9 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/QueryDefinitionRegistry2.java @@ -141,11 +141,6 @@ public static QueryDefinitionRegistry2 getInstance() { return registry; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder builder = new StringBuilder(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java index a2613f7a580..dbb872e4e47 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaDataNodeDefinition.java @@ -94,11 +94,6 @@ public String toString() { protected abstract String getDebugDumpClassName(); - @Override - public String debugDump() { - return debugDump(0); - } - public String getShortInfo() { StringBuilder sb = new StringBuilder(); sb.append(getDebugDumpClassName()).append(':').append(getJpaClassName()); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java index 16320ef4cf9..59251b5d754 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaEntityDefinition.java @@ -167,11 +167,6 @@ protected String getDebugDumpClassName() { return "Ent"; } - @Override - public String debugDump() { - return debugDump(0); - } - public boolean isAssignableFrom(JpaEntityDefinition specificEntityDefinition) { return getJpaClass().isAssignableFrom(specificEntityDefinition.getJpaClass()); } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java index d6fdbf3f05f..b0e010a2d5f 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/definition/JpaLinkDefinition.java @@ -101,11 +101,6 @@ public void accept(Visitor visitor) { targetDefinition.accept(visitor); } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java index e94eb415b59..811143ce3df 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/HqlDataInstance.java @@ -63,11 +63,6 @@ HqlDataInstance getParentItem() { return parentDataItem; } - @Override - public String debugDump() { - return debugDump(0); - } - @SuppressWarnings("unused") public String debugDumpNoParent() { return debugDump(0, false); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java index 809faa37691..694eebdc1bd 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/resolution/ItemPathResolutionState.java @@ -110,11 +110,6 @@ public ItemPathResolutionState nextState(ItemDefinition itemDefinition, boolean itemPathResolver); } - @Override - public String debugDump() { - return debugDump(0); - } - String debugDumpNoParent() { return debugDump(0, false); } diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java index f96d1eba889..77949025cd7 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/DummyAuditService.java @@ -472,11 +472,6 @@ public String toString() { return "DummyAuditService(" + records + ")"; } - @Override - public String debugDump() { - return debugDump(0); - } - @Override public String debugDump(int indent) { StringBuilder sb = new StringBuilder(); From 5b32c5b61fd6c91ed9a4d51a20a230ec07befcaf Mon Sep 17 00:00:00 2001 From: Tony Tkacik Date: Thu, 27 Feb 2020 09:20:51 +0100 Subject: [PATCH 02/55] Removed raw types use Signed-off-by: Tony Tkacik --- .../com/evolveum/midpoint/repo/sql/AddGetObjectTest.java | 8 +++----- .../midpoint/repo/sql/util/PrismIdentifierGenerator.java | 2 +- .../com/evolveum/midpoint/test/IntegrationTestTools.java | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java index 8037824b992..5b7f35f8d5f 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/AddGetObjectTest.java @@ -237,7 +237,7 @@ private void checkContainerValuesSize(QName parentName, PrismContainerValue n } } - private void checkContainersSize(PrismContainer newContainer, PrismContainer oldContainer) { + private void checkContainersSize(PrismContainer newContainer, PrismContainer oldContainer) { logger.info("checkContainersSize {} new {} old {}", newContainer.getElementName(), newContainer.size(), oldContainer.size()); AssertJUnit.assertEquals(newContainer.size(), oldContainer.size()); @@ -248,16 +248,14 @@ private void checkContainersSize(PrismContainer newContainer, PrismContainer old return; } List checked = new ArrayList<>(); - List newValues = newContainer.getValues(); - for (PrismContainerValue value : newValues) { + for (PrismContainerValue value : newContainer.getValues()) { PrismContainerValue oldValue = oldContainer.getValue(value.getId()); checkContainerValuesSize(newContainer.getElementName(), value, oldValue); checked.add(value.getId()); } - List oldValues = oldContainer.getValues(); - for (PrismContainerValue value : oldValues) { + for (PrismContainerValue value : oldContainer.getValues()) { if (checked.contains(value.getId())) { continue; } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java index b63e8742194..36dd90e011b 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/util/PrismIdentifierGenerator.java @@ -82,7 +82,7 @@ private List> listAllPrismContainers(Visitable object) { return; } - PrismContainer container = (PrismContainer) visitable; + PrismContainer container = (PrismContainer) visitable; PrismContainerDefinition def = container.getDefinition(); if (def.isSingleValue()) { return; diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java index 27804f85812..a47d322560a 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/IntegrationTestTools.java @@ -322,7 +322,7 @@ public static void assertProvisioningAccountShadow(PrismObject accou public static void assertProvisioningShadow(PrismObject account, Class expectedAttributeDefinitionClass, QName objectClass) { // Check attribute definition - PrismContainer attributesContainer = account.findContainer(ShadowType.F_ATTRIBUTES); + PrismContainer attributesContainer = account.findContainer(ShadowType.F_ATTRIBUTES); PrismAsserts.assertClass("Wrong attributes container class", ResourceAttributeContainer.class, attributesContainer); ResourceAttributeContainer rAttributesContainer = (ResourceAttributeContainer) attributesContainer; PrismContainerDefinition attrsDef = attributesContainer.getDefinition(); From 4a99b9d7b0c345ba3e1bba227d52ebeae3f4f2e8 Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Thu, 5 Mar 2020 17:47:16 +0100 Subject: [PATCH 03/55] Make swallowToPrimaryDelta work with frozen deltas Primary deltas are now frozen in lens element contexts. But we sometimes need to modify them e.g. in scripting hooks. The swallowToPrimaryDelta was changed to allow this. Resolves MID-6097. --- .../model/impl/lens/LensElementContext.java | 31 +++++++++++++++++-- 1 file changed, 28 insertions(+), 3 deletions(-) diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java index e5f5303b2df..6057cea6f9d 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java @@ -259,11 +259,36 @@ public void addPrimaryDelta(ObjectDelta delta) throws SchemaException { } public void swallowToPrimaryDelta(ItemDelta itemDelta) throws SchemaException { + createOrModifyPrimaryDelta( + delta -> delta.swallow(itemDelta), + () -> { + ObjectDelta newPrimaryDelta = getPrismContext().deltaFactory().object().create(getObjectTypeClass(), ChangeType.MODIFY); + newPrimaryDelta.setOid(oid); + newPrimaryDelta.addModification(itemDelta); + return newPrimaryDelta; + }); + } + + @FunctionalInterface + private interface DeltaModifier { + void modify(ObjectDelta delta) throws SchemaException; + } + + @FunctionalInterface + private interface DeltaCreator { + ObjectDelta create() throws SchemaException; + } + + private void createOrModifyPrimaryDelta(DeltaModifier modifier, DeltaCreator creator) throws SchemaException { if (primaryDelta == null) { - primaryDelta = getPrismContext().deltaFactory().object().create(getObjectTypeClass(), ChangeType.MODIFY); - primaryDelta.setOid(oid); + primaryDelta = creator.create(); + } else if (!primaryDelta.isImmutable()) { + modifier.modify(primaryDelta); + } else { + primaryDelta = primaryDelta.clone(); + modifier.modify(primaryDelta); + primaryDelta.freeze(); } - primaryDelta.swallow(itemDelta); } public abstract void swallowToSecondaryDelta(ItemDelta itemDelta) throws SchemaException; From 0123917e577e292b1c9599d9deeaf7d4d1b5836a Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Thu, 5 Mar 2020 18:48:05 +0100 Subject: [PATCH 04/55] Do a cosmetic method rename --- .../evolveum/midpoint/model/impl/lens/LensElementContext.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java index 6057cea6f9d..ba5355cdc3e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java @@ -259,7 +259,7 @@ public void addPrimaryDelta(ObjectDelta delta) throws SchemaException { } public void swallowToPrimaryDelta(ItemDelta itemDelta) throws SchemaException { - createOrModifyPrimaryDelta( + modifyOrCreatePrimaryDelta( delta -> delta.swallow(itemDelta), () -> { ObjectDelta newPrimaryDelta = getPrismContext().deltaFactory().object().create(getObjectTypeClass(), ChangeType.MODIFY); @@ -279,7 +279,7 @@ private interface DeltaCreator { ObjectDelta create() throws SchemaException; } - private void createOrModifyPrimaryDelta(DeltaModifier modifier, DeltaCreator creator) throws SchemaException { + private void modifyOrCreatePrimaryDelta(DeltaModifier modifier, DeltaCreator creator) throws SchemaException { if (primaryDelta == null) { primaryDelta = creator.create(); } else if (!primaryDelta.isImmutable()) { From 69a9c3fdd82f68bbed3d4a811400b1bb9cd99b98 Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Thu, 5 Mar 2020 19:06:34 +0100 Subject: [PATCH 05/55] Fix failing TestScriptingBasic Relation in test394AssignToWill2 was not specified correctly (and worked on master only by chance). --- .../impl/scripting/actions/AssignExecutor.java | 4 ++-- .../model/intest/scripting/TestScriptingBasic.java | 14 +------------- .../test/resources/scripting/assign-to-will-2.xml | 2 +- .../resources/scripting/system-configuration.xml | 8 +++++++- 4 files changed, 11 insertions(+), 17 deletions(-) diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/AssignExecutor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/AssignExecutor.java index a044c27c272..0e863887967 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/AssignExecutor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/scripting/actions/AssignExecutor.java @@ -129,13 +129,13 @@ protected String getName() { @Override protected ObjectDelta createDelta(AssignmentHolderType objectType, Collection resources, Collection roles, Collection relations) throws ScriptExecutionException { - String relation = ""; + String relation; if (relations == null || relations.isEmpty()) { QName defaultRelation = prismContext.getDefaultRelation() != null ? prismContext.getDefaultRelation() : RelationTypes.MEMBER.getRelation(); relation = QNameUtil.qNameToUri(defaultRelation); - } else if(relations.size() > 1){ + } else if (relations.size() > 1) { throw new IllegalArgumentException("Couldn't use relation as multivalue parameter"); } else { relation = relations.iterator().next(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java index d11a0ac5367..bb1ab8b053f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/scripting/TestScriptingBasic.java @@ -642,24 +642,12 @@ public void test393UnassignFromWill3() throws Exception { @Test public void test394AssignToWill2() throws Exception { // GIVEN - QName customRelation = new QName("http://midpoint.evolveum.com/xml/ns/samples/piracy", "piracy:captain"); + QName customRelation = new QName("http://midpoint.evolveum.com/xml/ns/samples/piracy", "captain"); Task task = getTestTask(); OperationResult result = task.getResult(); PrismProperty expression = parseAnyData(ASSIGN_TO_WILL_2_FILE); - PrismObject systemConfig = repositoryService.getObject(SystemConfigurationType.class, - SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, result); - RoleManagementConfigurationType roleManagement = systemConfig.asObjectable().getRoleManagement(); - PrismContainerValue oldValue = systemConfig.asObjectable().getRoleManagement().asPrismContainerValue(); - roleManagement.beginRelations().beginRelation().setRef(customRelation); - Collection modifications = new ArrayList<>(); - ContainerDelta deleteDelta = prismContext.deltaFactory().container().createModificationReplace(SystemConfigurationType.F_ROLE_MANAGEMENT, - SystemConfigurationType.class, oldValue.clone()); - ((Collection) modifications).add(deleteDelta); - modifySystemObjectInRepo(SystemConfigurationType.class, - SystemObjectsType.SYSTEM_CONFIGURATION.value(), modifications, result); - // WHEN ExecutionContext output = scriptingExpressionEvaluator.evaluateExpression(expression.getAnyValue().getValue(), task, result); diff --git a/model/model-intest/src/test/resources/scripting/assign-to-will-2.xml b/model/model-intest/src/test/resources/scripting/assign-to-will-2.xml index dfe5ec7da92..fa1e6d7f751 100644 --- a/model/model-intest/src/test/resources/scripting/assign-to-will-2.xml +++ b/model/model-intest/src/test/resources/scripting/assign-to-will-2.xml @@ -25,7 +25,7 @@ relation - piracy:captain + http://midpoint.evolveum.com/xml/ns/samples/piracy/captain diff --git a/model/model-intest/src/test/resources/scripting/system-configuration.xml b/model/model-intest/src/test/resources/scripting/system-configuration.xml index b75dc09c725..e09fb88bf0a 100644 --- a/model/model-intest/src/test/resources/scripting/system-configuration.xml +++ b/model/model-intest/src/test/resources/scripting/system-configuration.xml @@ -9,7 +9,8 @@ + xmlns:q="http://prism.evolveum.com/xml/ns/public/query-3" + xmlns:piracy="http://midpoint.evolveum.com/xml/ns/samples/piracy"> SystemConfiguration @@ -393,6 +394,11 @@ false + + + piracy:captain + + From 20efabf8514e43295c0265a31b57297384c93129 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Thu, 5 Mar 2020 23:48:28 +0100 Subject: [PATCH 06/55] next batch of test classes cleanup, TEST_NAME, reformat, etc. - forgotten dangling X.class.getName() statements were removed - EMPTY_PATH final local variables renamed to emptyPath - some older unused methods were removed --- .../midpoint/prism/xml/XmlTypeConverter.java | 4 +- .../midpoint/schema/GetOperationOptions.java | 72 ++--- .../midpoint/schema/SelectorOptions.java | 36 +-- .../common/expression/TestExpressionUtil.java | 22 +- .../model/common/mapping/TestMappingTime.java | 151 +++++----- ...actModelImplementationIntegrationTest.java | 110 ++++---- .../lens/TestAbstractAssignmentEvaluator.java | 233 +++++++--------- .../model/impl/lens/TestAssignedMappings.java | 57 +--- .../impl/lens/TestAssignmentProcessor.java | 200 ++++++-------- .../model/impl/lens/TestClockwork.java | 138 ++++------ .../model/impl/lens/TestDependencies.java | 106 +++---- .../model/impl/lens/TestPolicyRules2.java | 120 +++----- .../model/impl/lens/TestProjector.java | 130 ++------- .../model/impl/lens/TestProjectorPersona.java | 28 +- .../lens/TestProjectorRoleEntitlement.java | 36 +-- .../model/impl/lens/TestReconScript.java | 92 +++---- .../impl/misc/ShadowIntegrityCheckerTest.java | 31 +-- .../model/impl/misc/TestCaseManagement.java | 24 +- .../model/impl/misc/TestRelationRegistry.java | 10 - .../TestAbstractAuthenticationEvaluator.java | 16 -- .../TestGuiProfiledPrincipalManager.java | 72 +++-- .../TestCorrelationConfirmationEvaluator.java | 65 ++--- .../impl/sync/TestSynchronizationService.java | 31 +-- ...bstractConfiguredModelIntegrationTest.java | 3 - ...stractInitializedModelIntegrationTest.java | 4 - .../midpoint/model/intest/TestActivation.java | 48 +--- .../midpoint/model/intest/TestDeputy.java | 1 - .../intest/TestOptimizingTriggerCreator.java | 7 - .../model/intest/TestTriggerTask.java | 77 +----- .../midpoint/model/intest/TestVolatility.java | 41 --- .../async/TestAsyncUpdateGrouperJson.java | 199 +++++++------- .../model/intest/multi/TestMultiAccount.java | 258 ++++++++--------- .../intest/password/AbstractPasswordTest.java | 3 - .../midpoint/model/intest/rbac/TestRbac.java | 15 +- .../intest/rbac/TestSegregationOfDuties.java | 32 +-- .../intest/sync/AbstractInboundSyncTest.java | 83 +----- .../sync/AbstractObjTemplateSyncTest.java | 17 -- .../AbstractSynchronizationStoryTest.java | 260 +++--------------- .../intest/sync/TestInboundLiveSyncTask.java | 6 - .../intest/sync/TestInboundReconTask.java | 14 - .../model/intest/sync/TestLiveSyncTask.java | 5 - .../sync/TestLiveSyncTaskMechanics.java | 10 - .../midpoint/model/intest/sync/TestUuid.java | 152 ++++------ .../sync/TestValidityRecomputeTask.java | 5 +- .../test/AbstractModelIntegrationTest.java | 207 ++++++++------ .../AbstractTestAssignmentApproval.java | 8 +- .../assignments/TestAssignmentsAdvanced.java | 8 +- .../wf/impl/other/TestDelegation.java | 2 +- .../wf/impl/other/TestEscalation.java | 4 +- .../midpoint/wf/impl/other/TestEvents.java | 2 +- .../wf/impl/other/TestMiscellaneous.java | 16 +- .../wf/impl/other/TestParallelApprovals.java | 18 +- .../midpoint/wf/impl/other/TestSoD.java | 6 +- .../impl/dummy/AbstractDummyTest.java | 1 - .../dummy/TestDummyUuidNonUniqueName.java | 4 +- .../common/expression/ExpressionUtil.java | 140 ++++------ .../sql/helpers/NameResolutionHelper.java | 4 +- .../testing/story/TestPhotoAssignment.java | 22 +- .../story/TestServiceAccountsClassifier.java | 6 +- .../testing/story/TestThresholds.java | 2 - .../testing/story/ldap/AbstractLdapTest.java | 53 ++-- 61 files changed, 1223 insertions(+), 2304 deletions(-) diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java index 96383d23cf6..22a30976ca6 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java @@ -266,9 +266,7 @@ public static String fromXmlEnum(T enumValue) { Field field; try { field = enumValue.getClass().getField(fieldName); - } catch (SecurityException e) { - throw new IllegalArgumentException("Error getting field from "+enumValue, e); - } catch (NoSuchFieldException e) { + } catch (SecurityException | NoSuchFieldException e) { throw new IllegalArgumentException("Error getting field from "+enumValue, e); } XmlEnumValue annotation = field.getAnnotation(XmlEnumValue.class); diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/GetOperationOptions.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/GetOperationOptions.java index d3b123645dd..76ebc49d9a4 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/GetOperationOptions.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/GetOperationOptions.java @@ -6,26 +6,26 @@ */ package com.evolveum.midpoint.schema; +import java.io.Serializable; +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Objects; + +import org.apache.commons.collections4.CollectionUtils; +import org.jetbrains.annotations.NotNull; + import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.path.UniformItemPath; import com.evolveum.midpoint.prism.path.ItemPathCollectionsUtil; +import com.evolveum.midpoint.prism.path.UniformItemPath; import com.evolveum.midpoint.util.ShortDumpable; import com.evolveum.midpoint.util.annotation.Experimental; import com.evolveum.midpoint.xml.ns._public.common.common_3.GetOperationOptionsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.IterationMethodType; -import org.apache.commons.collections4.CollectionUtils; -import org.jetbrains.annotations.NotNull; - -import java.io.Serializable; -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Objects; /** * @author semancik - * */ public class GetOperationOptions extends AbstractOptions implements Serializable, Cloneable, ShortDumpable { private static final long serialVersionUID = 1L; @@ -129,7 +129,7 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * The default value is zero, which means that a fresh value must always be returned. This means that caches that do * not guarantee fresh value cannot be used. If non-zero value is specified then such caches may be used. In case that * Long.MAX_VALUE is specified then the caches are always used and fresh value is never retrieved. - * + *

* Null value is special in one more aspect: it allows to return partial cached data in case that the original is not * accessible. E.g. in that case provisioning can return repository shadow in case that the resource is not reachable. * Explicit specification of staleness=0 disables this behavior. @@ -158,11 +158,11 @@ public class GetOperationOptions extends AbstractOptions implements Serializable /** * Should the results be made distinct. * Not all providers support this option. - * + *

* BEWARE: - * - may bring a potentially huge performance penalty - * - may interfere with paging (!) - * + * - may bring a potentially huge performance penalty + * - may interfere with paging (!) + *

* So please consider this option an EXPERIMENTAL, for now. */ @Experimental @@ -187,7 +187,7 @@ public class GetOperationOptions extends AbstractOptions implements Serializable * Whether this operation is already part of the execution phase. I.e. the request authorization was already * processed. This means that the operation is in fact operation invoked within another operation, * e.g. invoked from script or expression evaluator. - * + *

* WARNING: THIS OPTION MUST NOT BE AVAILABLE FROM REMOTE INTERFACES. * This is safe to use from a secure area of JVM, where the components can trick model to circumvent * authorizations anyway. But it must not be available outside of the secure area. @@ -358,11 +358,11 @@ public static boolean isNoFetch(GetOperationOptions options) { return options.noFetch; } - /** - * No not fetch any information from external sources, e.g. do not fetch account data from resource, - * do not fetch resource schema, etc. - * Such operation returns only the data stored in midPoint repository. - */ + /** + * No not fetch any information from external sources, e.g. do not fetch account data from resource, + * do not fetch resource schema, etc. + * Such operation returns only the data stored in midPoint repository. + */ public static GetOperationOptions createNoFetch() { GetOperationOptions opts = new GetOperationOptions(); opts.setNoFetch(true); @@ -476,11 +476,11 @@ public static Collection> createRawCollecti return SelectorOptions.createCollection(createRaw()); } - /** - * No not fetch any information from external sources, e.g. do not fetch account data from resource, - * do not fetch resource schema, etc. - * Such operation returns only the data stored in midPoint repository. - */ + /** + * No not fetch any information from external sources, e.g. do not fetch account data from resource, + * do not fetch resource schema, etc. + * Such operation returns only the data stored in midPoint repository. + */ public static Collection> createNoFetchCollection() { return SelectorOptions.createCollection(createNoFetch()); } @@ -756,11 +756,11 @@ public static boolean isDistinct(GetOperationOptions options) { /** * Should the results be made distinct. * Not all providers support this option. - * + *

* BEWARE: - * - may bring a potentially huge performance penalty - * - may interfere with paging (!) - * + * - may bring a potentially huge performance penalty + * - may interfere with paging (!) + *

* So please consider this option an EXPERIMENTAL, for now. */ @Experimental @@ -898,8 +898,8 @@ public GetOperationOptions relationalValueSearchQuery(RelationalValueSearchQuery @Override public boolean equals(Object o) { - if (this == o) return true; - if (!(o instanceof GetOperationOptions)) return false; + if (this == o) { return true; } + if (!(o instanceof GetOperationOptions)) { return false; } GetOperationOptions that = (GetOperationOptions) o; return retrieve == that.retrieve && Objects.equals(resolve, that.resolve) && @@ -1033,23 +1033,23 @@ public static GetOperationOptions fromRestOptions(List options, Definiti return rv; } - @NotNull @SafeVarargs public static Collection> merge(PrismContext prismContext, Collection>... parts) { - final UniformItemPath EMPTY_PATH = prismContext.emptyPath(); + final UniformItemPath emptyPath = prismContext.emptyPath(); Collection> merged = new ArrayList<>(); for (Collection> part : parts) { for (SelectorOptions increment : CollectionUtils.emptyIfNull(part)) { if (increment != null) { // should always be so - Collection existing = SelectorOptions.findOptionsForPath(merged, increment.getItemPath(EMPTY_PATH)); + Collection existing = SelectorOptions.findOptionsForPath( + merged, increment.getItemPath(emptyPath)); if (existing.isEmpty()) { merged.add(increment); } else if (existing.size() == 1) { existing.iterator().next().merge(increment.getOptions()); } else { - throw new AssertionError("More than one options for path: " + increment.getItemPath(EMPTY_PATH)); + throw new AssertionError("More than one options for path: " + increment.getItemPath(emptyPath)); } } } diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/SelectorOptions.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/SelectorOptions.java index d7acbd9ed30..18070d658d5 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/SelectorOptions.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/SelectorOptions.java @@ -6,30 +6,32 @@ */ package com.evolveum.midpoint.schema; +import static com.evolveum.midpoint.util.MiscUtil.emptyIfNull; + import java.io.Serializable; -import java.util.*; import java.util.Objects; +import java.util.*; import java.util.function.Consumer; import java.util.function.Function; import java.util.function.Supplier; import java.util.stream.Collectors; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.path.*; -import com.evolveum.midpoint.util.DebugDumpable; -import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.util.ShortDumpable; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang3.ObjectUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import static com.evolveum.midpoint.util.MiscUtil.emptyIfNull; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.path.ItemPathCollectionsUtil; +import com.evolveum.midpoint.prism.path.UniformItemPath; +import com.evolveum.midpoint.util.DebugDumpable; +import com.evolveum.midpoint.util.MiscUtil; +import com.evolveum.midpoint.util.ShortDumpable; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ public class SelectorOptions implements Serializable, DebugDumpable, ShortDumpable { private static final long serialVersionUID = 1L; @@ -72,7 +74,7 @@ public static Collection> createCollection(T options) { public static Collection> createCollection(T options, UniformItemPath... paths) { Collection> optionsCollection = new ArrayList<>(paths.length); - for (UniformItemPath path: paths) { + for (UniformItemPath path : paths) { optionsCollection.add(create(path, options)); } return optionsCollection; @@ -128,7 +130,7 @@ public static T findRootOptions(Collection> options) { if (options == null) { return null; } - for (SelectorOptions oooption: options) { + for (SelectorOptions oooption : options) { if (oooption.isRoot()) { return oooption.getOptions(); } @@ -156,7 +158,7 @@ public static Collection> updateRootOptions(Collection Collection findOptionsForPath(Collection> options, @NotNull UniformItemPath path) { Collection rv = new ArrayList<>(); - for (SelectorOptions oooption: CollectionUtils.emptyIfNull(options)) { + for (SelectorOptions oooption : CollectionUtils.emptyIfNull(options)) { if (path.equivalent(oooption.getItemPathOrNull())) { rv.add(oooption.getOptions()); } @@ -229,12 +231,12 @@ public static List> filterRetrieveOptions( public static Map> extractOptionValues(Collection> options, Function supplier, PrismContext prismContext) { Map> rv = new HashMap<>(); - final UniformItemPath EMPTY_PATH = prismContext.emptyPath(); + final UniformItemPath emptyPath = prismContext.emptyPath(); for (SelectorOptions selectorOption : CollectionUtils.emptyIfNull(options)) { T value = supplier.apply(selectorOption.getOptions()); if (value != null) { Collection itemPaths = rv.computeIfAbsent(value, t -> new HashSet<>()); - itemPaths.add(selectorOption.getItemPath(EMPTY_PATH)); + itemPaths.add(selectorOption.getItemPath(emptyPath)); } } return rv; @@ -245,8 +247,8 @@ public static Map> extractOptionValues(Collec //region hashCode, equals, toString @Override public boolean equals(Object o) { - if (this == o) return true; - if (o == null || getClass() != o.getClass()) return false; + if (this == o) { return true; } + if (o == null || getClass() != o.getClass()) { return false; } SelectorOptions that = (SelectorOptions) o; return Objects.equals(selector, that.selector) && Objects.equals(options, that.options); } @@ -280,7 +282,7 @@ public void shortDump(StringBuilder sb) { if (options == null) { sb.append("null"); } else if (options instanceof ShortDumpable) { - ((ShortDumpable)options).shortDump(sb); + ((ShortDumpable) options).shortDump(sb); } else { sb.append(options); } diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java index c8689207af0..283b91972ee 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/expression/TestExpressionUtil.java @@ -167,25 +167,31 @@ public void testResolvePathPolyStringOdoNorm() throws Exception { } - private T resolvePath(String path, final String TEST_NAME) - throws SchemaException, ObjectNotFoundException, IOException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + private T resolvePath(String path, final String exprShortDesc) + throws SchemaException, ObjectNotFoundException, IOException, CommunicationException, + ConfigurationException, SecurityViolationException, ExpressionEvaluationException { ExpressionVariables variables = createVariables(); - return resolvePath(path, variables, TEST_NAME); + return resolvePath(path, variables, exprShortDesc); } - private T resolvePathOdo(String path, final String TEST_NAME) throws SchemaException, ObjectNotFoundException, IOException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + private T resolvePathOdo(String path, final String exprShortDesc) + throws SchemaException, ObjectNotFoundException, IOException, CommunicationException, + ConfigurationException, SecurityViolationException, ExpressionEvaluationException { ExpressionVariables variables = createVariablesOdo(); - return resolvePath(path, variables, TEST_NAME); + return resolvePath(path, variables, exprShortDesc); } - private T resolvePath(String path, ExpressionVariables variables, final String TEST_NAME) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + private T resolvePath(String path, ExpressionVariables variables, String exprShortDesc) + throws SchemaException, ObjectNotFoundException, CommunicationException, + ConfigurationException, SecurityViolationException, ExpressionEvaluationException { OperationResult result = createOperationResult(); ItemPath itemPath = toItemPath(path); // WHEN ObjectResolver objectResolver = new DirectoryFileObjectResolver(MidPointTestConstants.OBJECTS_DIR); - Object resolved = ExpressionUtil.resolvePathGetValue(itemPath, variables, false, null, objectResolver, - PrismTestUtil.getPrismContext(), TEST_NAME, new NullTaskImpl(), result); + Object resolved = ExpressionUtil.resolvePathGetValue( + itemPath, variables, false, null, objectResolver, + PrismTestUtil.getPrismContext(), exprShortDesc, new NullTaskImpl(), result); // THEN IntegrationTestTools.display("Resolved", resolved); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java index 5028dbed3c7..8ddd90e0c7a 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java @@ -10,12 +10,8 @@ import static org.testng.AssertJUnit.assertNull; import java.io.IOException; - import javax.xml.datatype.XMLGregorianCalendar; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.test.NullTaskImpl; import org.testng.annotations.BeforeClass; import org.testng.annotations.Test; import org.xml.sax.SAXException; @@ -25,12 +21,15 @@ import com.evolveum.midpoint.prism.PrismPropertyValue; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; 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.schema.constants.ExpressionConstants; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.task.api.test.NullTaskImpl; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.exception.SchemaException; @@ -61,20 +60,17 @@ public void setupFactory() throws SAXException, IOException, SchemaException { @Test public void testBeforeTimeFrom() throws Exception { - final String TEST_NAME = "testBeforeTimeFrom"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); + UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_FROM_TO_FILENAME, - TEST_NAME, "title", delta); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_FROM_TO_FILENAME, getTestNameShort(), "title", delta); builder.setNow(TIME_PAST); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -93,20 +89,17 @@ private Task createTask() { @Test public void testBetweenTimes() throws Exception { - final String TEST_NAME = "testBetweenTimes"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); + UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_FROM_TO_FILENAME, - TEST_NAME, "title", delta); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_FROM_TO_FILENAME, getTestNameShort(), "title", delta); builder.setNow(TIME_BETWEEN); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -116,28 +109,25 @@ public void testBetweenTimes() throws Exception { // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); - PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("CAPTAIN")); - PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("PIRATE")); + PrismAsserts.assertTriplePlus(outputTriple, PrismTestUtil.createPolyString("CAPTAIN")); + PrismAsserts.assertTripleMinus(outputTriple, PrismTestUtil.createPolyString("PIRATE")); assertNextRecompute(mapping, TIME_MAPPING_DISABLED_PLUS_10D); } @Test public void testAfterTimeTo() throws Exception { - final String TEST_NAME = "testAfterTimeTo"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); + UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_FROM_TO_FILENAME, - TEST_NAME, "title", delta); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_FROM_TO_FILENAME, getTestNameShort(), "title", delta); builder.setNow(TIME_FUTURE); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -153,21 +143,19 @@ public void testAfterTimeTo() throws Exception { @Test public void testExistenceBefore() throws Exception { - final String TEST_NAME = "testExistenceBefore"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, - TEST_NAME, "title", null); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_ACTIVATION, getTestNameShort(), "title", null); builder.setNow(TIME_PAST); - PrismPropertyDefinition existenceDef = evaluator.getPrismContext().definitionFactory().createPropertyDefinition( - ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); + PrismPropertyDefinition existenceDef = + evaluator.getPrismContext().definitionFactory().createPropertyDefinition( + ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); builder.setDefaultTargetDefinition(existenceDef); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -183,21 +171,19 @@ public void testExistenceBefore() throws Exception { @Test public void testExistenceAfter() throws Exception { - final String TEST_NAME = "testExistenceAfter"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, - TEST_NAME, "title", null); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_ACTIVATION, getTestNameShort(), "title", null); builder.setNow(TIME_FUTURE); - PrismPropertyDefinition existenceDef = evaluator.getPrismContext().definitionFactory().createPropertyDefinition( - ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); + PrismPropertyDefinition existenceDef = + evaluator.getPrismContext().definitionFactory().createPropertyDefinition( + ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); builder.setDefaultTargetDefinition(existenceDef); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -207,33 +193,30 @@ public void testExistenceAfter() throws Exception { // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleZero(outputTriple, false); - PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoPlus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); assertNextRecompute(mapping, null); } @Test public void testNoReferenceTime() throws Exception { - final String TEST_NAME = "testNoReferenceTime"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN - PrismObject userOld = evaluator.getUserOld(); userOld.asObjectable().getActivation().setDisableTimestamp(null); - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, - TEST_NAME, "title", null, userOld); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_ACTIVATION, getTestNameShort(), "title", null, userOld); builder.setNow(TIME_PAST); - PrismPropertyDefinition existenceDef = evaluator.getPrismContext().definitionFactory().createPropertyDefinition( - ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); + PrismPropertyDefinition existenceDef = + evaluator.getPrismContext().definitionFactory().createPropertyDefinition( + ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); builder.setDefaultTargetDefinition(existenceDef); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -249,31 +232,28 @@ public void testNoReferenceTime() throws Exception { @Test public void testSetReferenceTimeBefore() throws Exception { - final String TEST_NAME = "testSetReferenceTimeBefore"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN - PrismObject userOld = evaluator.getUserOld(); XMLGregorianCalendar disableTimestamp = userOld.asObjectable().getActivation().getDisableTimestamp(); userOld.asObjectable().getActivation().setDisableTimestamp(null); ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - ItemPath.create(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), + ItemPath.create(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), disableTimestamp); - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, - TEST_NAME, "title", delta, userOld); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_ACTIVATION, getTestNameShort(), "title", delta, userOld); builder.setNow(TIME_PAST); - PrismPropertyDefinition existenceDef = evaluator.getPrismContext().definitionFactory().createPropertyDefinition( - ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); + PrismPropertyDefinition existenceDef = + evaluator.getPrismContext().definitionFactory().createPropertyDefinition( + ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); builder.setDefaultTargetDefinition(existenceDef); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -289,9 +269,6 @@ public void testSetReferenceTimeBefore() throws Exception { @Test public void testSetReferenceTimeAfter() throws Exception { - final String TEST_NAME = "testSetReferenceTimeAfter"; - System.out.println("===[ "+TEST_NAME+"]==="); - // GIVEN PrismObject userOld = evaluator.getUserOld(); XMLGregorianCalendar disableTimestamp = userOld.asObjectable().getActivation().getDisableTimestamp(); @@ -299,20 +276,21 @@ public void testSetReferenceTimeAfter() throws Exception { ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, - ItemPath.create(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), + ItemPath.create(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), disableTimestamp); - MappingImpl.Builder,PrismPropertyDefinition> builder = evaluator.createMappingBuilder( - MAPPING_TIME_ACTIVATION, - TEST_NAME, "title", delta, userOld); + MappingImpl.Builder, PrismPropertyDefinition> builder = + evaluator.createMappingBuilder( + MAPPING_TIME_ACTIVATION, getTestNameShort(), "title", delta, userOld); builder.setNow(TIME_FUTURE); - PrismPropertyDefinition existenceDef = evaluator.getPrismContext().definitionFactory().createPropertyDefinition( - ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); + PrismPropertyDefinition existenceDef = + evaluator.getPrismContext().definitionFactory().createPropertyDefinition( + ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); builder.setDefaultTargetDefinition(existenceDef); - MappingImpl,PrismPropertyDefinition> mapping = builder.build(); + MappingImpl, PrismPropertyDefinition> mapping = builder.build(); OperationResult opResult = new OperationResult(contextName()); @@ -322,19 +300,18 @@ public void testSetReferenceTimeAfter() throws Exception { // THEN PrismValueDeltaSetTriple> outputTriple = mapping.getOutputTriple(); PrismAsserts.assertTripleZero(outputTriple, false); - PrismAsserts.assertTripleNoPlus(outputTriple); - PrismAsserts.assertTripleNoMinus(outputTriple); + PrismAsserts.assertTripleNoPlus(outputTriple); + PrismAsserts.assertTripleNoMinus(outputTriple); assertNextRecompute(mapping, null); } private void assertNullTriple(PrismValueDeltaSetTriple outputTriple) { - assertNull("Unexpected output triple: "+outputTriple, outputTriple); + assertNull("Unexpected output triple: " + outputTriple, outputTriple); } - private void assertNextRecompute(MappingImpl mapping, XMLGregorianCalendar expected) { + private void assertNextRecompute(MappingImpl mapping, XMLGregorianCalendar expected) { XMLGregorianCalendar nextRecomputeTime = mapping.getNextRecomputeTime(); - assertEquals("Wrong nextRecomputeTime in mapping "+mapping, expected, nextRecomputeTime); + assertEquals("Wrong nextRecomputeTime in mapping " + mapping, expected, nextRecomputeTime); } - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractModelImplementationIntegrationTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractModelImplementationIntegrationTest.java index 88e403826a4..0a9d902a905 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractModelImplementationIntegrationTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractModelImplementationIntegrationTest.java @@ -6,6 +6,17 @@ */ package com.evolveum.midpoint.model.impl; +import static org.testng.AssertJUnit.*; + +import java.io.File; +import java.io.IOException; +import java.util.Collection; +import java.util.List; +import java.util.function.Consumer; +import javax.xml.namespace.QName; + +import org.jetbrains.annotations.NotNull; + import com.evolveum.midpoint.common.crypto.CryptoUtil; import com.evolveum.midpoint.common.refinery.RefinedAttributeDefinition; import com.evolveum.midpoint.common.refinery.RefinedObjectClassDefinition; @@ -21,26 +32,18 @@ import com.evolveum.midpoint.prism.delta.PropertyDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.*; +import com.evolveum.midpoint.schema.DeltaConvertor; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.ResourceShadowDiscriminator; +import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.result.OperationResult; 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.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectModificationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.jetbrains.annotations.NotNull; - -import javax.xml.bind.JAXBException; -import javax.xml.namespace.QName; -import java.io.File; -import java.io.FileNotFoundException; -import java.io.IOException; -import java.util.Collection; -import java.util.List; -import java.util.function.Consumer; - -import static org.testng.AssertJUnit.*; /** * An enhancement of AbstractModelIntegrationTest (i.e. model-api-level test) that contains various useful @@ -64,8 +67,8 @@ protected LensContext createUserLensContext() { return new LensContext<>(UserType.class, prismContext, provisioningService); } - protected LensFocusContext fillContextWithFocus(LensContext context, PrismObject focus) - throws SchemaException, ObjectNotFoundException { + protected LensFocusContext fillContextWithFocus( + LensContext context, PrismObject focus) { LensFocusContext focusContext = context.getOrCreateFocusContext(); focusContext.setLoadedObject(focus); return focusContext; @@ -83,14 +86,14 @@ protected LensFocusContext fillContextWithUser(LensContext c return fillContextWithFocus(context, UserType.class, userOid, result); } - - protected void fillContextWithFocus(LensContext context, File file) throws SchemaException, - ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, IOException { + @UnusedTestElement + protected void fillContextWithFocus(LensContext context, File file) + throws SchemaException, IOException { PrismObject user = PrismTestUtil.parseObject(file); fillContextWithFocus(context, user); } - protected void fillContextWithEmtptyAddUserDelta(LensContext context, OperationResult result) throws SchemaException { + protected void fillContextWithEmtptyAddUserDelta(LensContext context) throws SchemaException { ObjectDelta userDelta = prismContext.deltaFactory().object() .createEmptyAddDelta(UserType.class, null ); @@ -98,14 +101,14 @@ protected void fillContextWithEmtptyAddUserDelta(LensContext context, focusContext.setPrimaryDelta(userDelta); } - protected void fillContextWithAddUserDelta(LensContext context, PrismObject user) throws SchemaException, EncryptionException { + protected void fillContextWithAddUserDelta(LensContext context, PrismObject user) throws EncryptionException { CryptoUtil.encryptValues(protector, user); ObjectDelta userDelta = DeltaFactory.Object.createAddDelta(user); LensFocusContext focusContext = context.getOrCreateFocusContext(); focusContext.setPrimaryDelta(userDelta); } - protected void fillContextWithAddDelta(LensContext context, PrismObject object) throws SchemaException, EncryptionException { + protected void fillContextWithAddDelta(LensContext context, PrismObject object) throws EncryptionException { CryptoUtil.encryptValues(protector, object); ObjectDelta addDelta = DeltaFactory.Object.createAddDelta(object); LensFocusContext focusContext = context.getOrCreateFocusContext(); @@ -119,15 +122,17 @@ protected LensProjectionContext fillContextWithAccount(LensContext con return fillContextWithAccount(context, account, task, result); } - protected LensProjectionContext fillContextWithAccountFromFile(LensContext context, File file, Task task, OperationResult result) throws SchemaException, - ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, IOException, ExpressionEvaluationException { + protected LensProjectionContext fillContextWithAccountFromFile( + LensContext context, File file, Task task, OperationResult result) + throws ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, + ConfigurationException, SecurityViolationException, IOException, SchemaException { PrismObject account = PrismTestUtil.parseObject(file); provisioningService.applyDefinition(account, task, result); return fillContextWithAccount(context, account, task, result); } protected LensProjectionContext fillContextWithAccount(LensContext context, PrismObject account, Task task, OperationResult result) throws SchemaException, - ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { ShadowType accountType = account.asObjectable(); String resourceOid = accountType.getResourceRef().getOid(); ResourceType resourceType = provisioningService.getObject(ResourceType.class, resourceOid, null, task, result).asObjectable(); @@ -145,7 +150,7 @@ protected LensProjectionContext fillContextWithAccount(LensContext con protected ObjectDelta addFocusModificationToContext( LensContext context, File file) - throws JAXBException, SchemaException, IOException { + throws SchemaException, IOException { ObjectModificationType modElement = PrismTestUtil.parseAtomicValue( file, ObjectModificationType.COMPLEX_TYPE); ObjectDelta focusDelta = DeltaConvertor.createObjectDelta( @@ -166,26 +171,20 @@ protected ObjectDelta addModificationToContextReplaceUserProperty( LensFocusContext focusContext = context.getOrCreateFocusContext(); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, focusContext - .getObjectOld().getOid(), propertyPath, propertyValues); + .getObjectOld().getOid(), propertyPath, propertyValues); focusContext.addPrimaryDelta(userDelta); return userDelta; } protected ObjectDelta addModificationToContextAddAccountFromFile( - LensContext context, String filename) throws JAXBException, SchemaException, - IOException { - return addModificationToContextAddProjection(context, UserType.class, new File(filename)); - } - - protected ObjectDelta addModificationToContextAddAccountFromFile( - LensContext context, File file) throws JAXBException, SchemaException, - IOException { + LensContext context, File file) + throws SchemaException, IOException { return addModificationToContextAddProjection(context, UserType.class, file); } protected ObjectDelta addModificationToContextAddProjection( - LensContext context, Class focusType, File file) throws JAXBException, SchemaException, - IOException { + LensContext context, Class focusType, File file) + throws SchemaException, IOException { PrismObject account = PrismTestUtil.parseObject(file); account.trim(); account.checkConsistence(); @@ -197,8 +196,7 @@ protected ObjectDelta addModificationToContextAddProjec } protected ObjectDelta addModificationToContextDeleteAccount( - LensContext context, String accountOid) throws SchemaException, - FileNotFoundException { + LensContext context, String accountOid) throws SchemaException { LensProjectionContext accountCtx = context.findProjectionContextByOid(accountOid); ObjectDelta deleteAccountDelta = prismContext.deltaFactory().object().createDeleteDelta(ShadowType.class, accountOid); @@ -259,7 +257,7 @@ protected ObjectDelta createAccountDelta(LensProjectionContext a ItemPath attrPath = ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName); RefinedObjectClassDefinition refinedAccountDefinition = accCtx.getCompositeObjectClassDefinition(); RefinedAttributeDefinition attrDef = refinedAccountDefinition.findAttributeDefinition(attrQName); - assertNotNull("No definition of attribute "+attrQName+" in account def "+refinedAccountDefinition, attrDef); + assertNotNull("No definition of attribute " + attrQName + " in account def " + refinedAccountDefinition, attrDef); ObjectDelta accountDelta = prismContext.deltaFactory().object() .createEmptyModifyDelta(ShadowType.class, accountOid); PropertyDelta attrDelta = prismContext.deltaFactory().property().create(attrPath, attrDef); @@ -293,23 +291,7 @@ protected void assertNoUserPrimaryDelta(LensContext context) { assertTrue("User primary delta is not empty", userPrimaryDelta.isEmpty()); } - protected void assertUserPrimaryDelta(LensContext context) { - LensFocusContext focusContext = context.getFocusContext(); - ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - assertNotNull("User primary delta is null", userPrimaryDelta); - assertFalse("User primary delta is empty", userPrimaryDelta.isEmpty()); - } - - protected void assertNoUserSecondaryDelta(LensContext context) throws SchemaException { - LensFocusContext focusContext = context.getFocusContext(); - ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); - if (userSecondaryDelta == null) { - return; - } - assertTrue("User secondary delta is not empty", userSecondaryDelta.isEmpty()); - } - - protected void assertUserSecondaryDelta(LensContext context) throws SchemaException { + protected void assertUserSecondaryDelta(LensContext context) { LensFocusContext focusContext = context.getFocusContext(); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertNotNull("User secondary delta is null", userSecondaryDelta); @@ -317,21 +299,21 @@ protected void assertUserSecondaryDelta(LensContext context) throws Sc } @NotNull - protected LensContext createContextForRoleAssignment(String userOid, String roleOid, QName relation, - Consumer modificationBlock, OperationResult result) - throws SchemaException, ObjectNotFoundException, JAXBException, ConfigurationException { + protected LensContext createContextForRoleAssignment(String userOid, String roleOid, + QName relation, Consumer modificationBlock, OperationResult result) + throws SchemaException, ObjectNotFoundException, ConfigurationException { return createContextForAssignment(UserType.class, userOid, RoleType.class, roleOid, relation, modificationBlock, result); } @NotNull - protected LensContext createContextForAssignment(Class focusClass, String focusOid, - Class targetClass, String targetOid, QName relation, - Consumer modificationBlock, OperationResult result) - throws SchemaException, ObjectNotFoundException, JAXBException, ConfigurationException { + protected LensContext createContextForAssignment(Class focusClass, + String focusOid, Class targetClass, String targetOid, + QName relation, Consumer modificationBlock, OperationResult result) + throws SchemaException, ObjectNotFoundException, ConfigurationException { LensContext context = createLensContext(focusClass); fillContextWithFocus(context, focusClass, focusOid, result); QName targetType = prismContext.getSchemaRegistry().determineTypeForClass(targetClass); - assertNotNull("Unknown target class "+targetClass, targetType); + assertNotNull("Unknown target class " + targetClass, targetType); addFocusDeltaToContext(context, createAssignmentFocusDelta(focusClass, focusOid, targetOid, targetType, relation, modificationBlock, true)); context.recompute(); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java index 962958ebdb5..87ef0879626 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java @@ -6,32 +6,17 @@ */ package com.evolveum.midpoint.model.impl.lens; -import static com.evolveum.midpoint.prism.delta.PlusMinusZero.MINUS; -import static com.evolveum.midpoint.prism.delta.PlusMinusZero.PLUS; -import static com.evolveum.midpoint.prism.delta.PlusMinusZero.ZERO; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.prism.delta.PlusMinusZero.*; import static com.evolveum.midpoint.prism.xml.XmlTypeConverter.createDuration; import static com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType.F_ADMINISTRATIVE_STATUS; import static com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType.F_ACTIVATION; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; import java.io.File; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.HashSet; -import java.util.Set; - +import java.util.*; import javax.xml.namespace.QName; -import com.evolveum.midpoint.model.impl.lens.projector.AssignmentOrigin; -import com.evolveum.midpoint.model.impl.lens.projector.Projector; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.xml.XmlTypeConverter; -import com.evolveum.midpoint.schema.RelationRegistry; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; import org.springframework.test.annotation.DirtiesContext; @@ -43,29 +28,34 @@ import com.evolveum.midpoint.common.ActivationComputer; import com.evolveum.midpoint.common.Clock; import com.evolveum.midpoint.model.common.SystemObjectCache; -import com.evolveum.midpoint.model.common.mapping.MappingImpl; import com.evolveum.midpoint.model.common.mapping.MappingFactory; +import com.evolveum.midpoint.model.common.mapping.MappingImpl; import com.evolveum.midpoint.model.common.mapping.PrismValueDeltaSetTripleProducer; +import com.evolveum.midpoint.model.impl.lens.projector.AssignmentOrigin; +import com.evolveum.midpoint.model.impl.lens.projector.Projector; import com.evolveum.midpoint.model.impl.lens.projector.mappings.MappingEvaluator; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.delta.DeltaSetTriple; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PlusMinusZero; +import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.ItemDeltaItem; import com.evolveum.midpoint.prism.util.ObjectDeltaObject; import com.evolveum.midpoint.prism.util.PrismAsserts; +import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.repo.api.RepositoryService; import com.evolveum.midpoint.repo.common.ObjectResolver; +import com.evolveum.midpoint.schema.RelationRegistry; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ActivationUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class TestAbstractAssignmentEvaluator extends AbstractLensTest { @@ -110,10 +100,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100Direct() throws Exception { - final String TEST_NAME = "test100Direct"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -122,7 +110,7 @@ public void test100Direct() throws Exception { ObjectDeltaObject userOdo = createUserOdo(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); @@ -149,10 +137,8 @@ public void test100Direct() throws Exception { @Test public void test110DirectExpression() throws Exception { - final String TEST_NAME = "test110DirectExpression"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -162,7 +148,7 @@ public void test110DirectExpression() throws Exception { userOdo.recompute(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); @@ -188,10 +174,8 @@ public void test110DirectExpression() throws Exception { @Test public void test120DirectExpressionReplaceDescription() throws Exception { - final String TEST_NAME = "test120DirectExpressionReplaceDescription"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject user = userTypeJack.asPrismObject().clone(); @@ -201,12 +185,12 @@ public void test120DirectExpressionReplaceDescription() throws Exception { ItemPath path = ItemPath.create(UserType.F_ASSIGNMENT, 123L, AssignmentType.F_DESCRIPTION); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, USER_JACK_OID, - path, "captain"); + path, "captain"); ObjectDeltaObject userOdo = createUserOdo(user, userDelta); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); display("Assignment old", assignmentType); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); assignmentIdi.setResolvePath(UserType.F_ASSIGNMENT); assignmentIdi.setSubItemDeltas(userDelta.getModifications()); assignmentIdi.recompute(); @@ -223,19 +207,20 @@ public void test120DirectExpressionReplaceDescription() throws Exception { assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment); - assertEquals(1,evaluatedAssignment.getConstructionTriple().size()); + display("Evaluated assignment", evaluatedAssignment); + assertEquals(1, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(user); Construction construction = evaluatedAssignment.getConstructionTriple().getZeroSet().iterator().next(); assertNotNull("No object class definition in construction", construction.getRefinedObjectClassDefinition()); - assertEquals(1,construction.getAttributeMappings().size()); - MappingImpl, PrismPropertyDefinition> attributeMapping = (MappingImpl, PrismPropertyDefinition>) construction.getAttributeMappings().iterator().next(); + assertEquals(1, construction.getAttributeMappings().size()); + MappingImpl, PrismPropertyDefinition> attributeMapping = + (MappingImpl, PrismPropertyDefinition>) construction.getAttributeMappings().iterator().next(); PrismValueDeltaSetTriple> outputTriple = attributeMapping.getOutputTriple(); display("output triple", outputTriple); PrismAsserts.assertTripleNoZero(outputTriple); - PrismAsserts.assertTriplePlus(outputTriple, "The best captain the world has ever seen"); - PrismAsserts.assertTripleMinus(outputTriple, "The best pirate the world has ever seen"); + PrismAsserts.assertTriplePlus(outputTriple, "The best captain the world has ever seen"); + PrismAsserts.assertTripleMinus(outputTriple, "The best pirate the world has ever seen"); // the same using other words @@ -250,10 +235,8 @@ public void test120DirectExpressionReplaceDescription() throws Exception { @Test public void test130DirectExpressionReplaceDescriptionFromNull() throws Exception { - final String TEST_NAME = "test130DirectExpressionReplaceDescriptionFromNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject user = userTypeJack.asPrismObject().clone(); @@ -264,12 +247,12 @@ public void test130DirectExpressionReplaceDescriptionFromNull() throws Exception ItemPath path = ItemPath.create(UserType.F_ASSIGNMENT, 123L, AssignmentType.F_DESCRIPTION); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, USER_JACK_OID, - path, "sailor"); + path, "sailor"); ObjectDeltaObject userOdo = createUserOdo(user, userDelta); userOdo.recompute(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); assignmentIdi.setResolvePath(UserType.F_ASSIGNMENT); assignmentIdi.setSubItemDeltas(userDelta.getModifications()); assignmentIdi.recompute(); @@ -285,18 +268,19 @@ public void test130DirectExpressionReplaceDescriptionFromNull() throws Exception assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment); - assertEquals(1,evaluatedAssignment.getConstructionTriple().size()); + display("Evaluated assignment", evaluatedAssignment); + assertEquals(1, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(user); Construction construction = evaluatedAssignment.getConstructionTriple().getZeroSet().iterator().next(); assertNotNull("No object class definition in construction", construction.getRefinedObjectClassDefinition()); - assertEquals(1,construction.getAttributeMappings().size()); - PrismValueDeltaSetTripleProducer, PrismPropertyDefinition> attributeMapping = (PrismValueDeltaSetTripleProducer, PrismPropertyDefinition>) construction.getAttributeMappings().iterator().next(); + assertEquals(1, construction.getAttributeMappings().size()); + PrismValueDeltaSetTripleProducer, PrismPropertyDefinition> attributeMapping = + (PrismValueDeltaSetTripleProducer, PrismPropertyDefinition>) construction.getAttributeMappings().iterator().next(); PrismValueDeltaSetTriple> outputTriple = attributeMapping.getOutputTriple(); PrismAsserts.assertTripleNoZero(outputTriple); - PrismAsserts.assertTriplePlus(outputTriple, "The best sailor the world has ever seen"); - PrismAsserts.assertTripleMinus(outputTriple, "The best man the world has ever seen"); + PrismAsserts.assertTriplePlus(outputTriple, "The best sailor the world has ever seen"); + PrismAsserts.assertTripleMinus(outputTriple, "The best man the world has ever seen"); // the same using other words @@ -334,10 +318,8 @@ Explanation for roles structure (copied from role-corp-generic-metarole.xml) @Test public void test140RoleVisitor() throws Exception { - final String TEST_NAME = "test140RoleVisitor"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -346,12 +328,13 @@ public void test140RoleVisitor() throws Exception { ObjectDeltaObject userOdo = createUserOdo(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); - EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, - false, userTypeJack, TEST_NAME, AssignmentOrigin.createInObject(), task, result); + EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate( + assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, + getTestNameShort(), AssignmentOrigin.createInObject(), task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); // THEN @@ -359,7 +342,7 @@ public void test140RoleVisitor() throws Exception { assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals(1, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -379,10 +362,8 @@ public void test140RoleVisitor() throws Exception { @Test public void test142RoleVisitorDisabledAssignment() throws Exception { - final String TEST_NAME = "test142RoleVisitorDisabledAssignment"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -392,12 +373,13 @@ public void test142RoleVisitorDisabledAssignment() throws Exception { ObjectDeltaObject userOdo = createUserOdo(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); - EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, - false, userTypeJack, TEST_NAME, AssignmentOrigin.createInObject(), task, result); + EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate( + assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, + getTestNameShort(), AssignmentOrigin.createInObject(), task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); // THEN @@ -406,7 +388,7 @@ public void test142RoleVisitorDisabledAssignment() throws Exception { TestUtil.assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals(1, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -426,10 +408,8 @@ public void test142RoleVisitorDisabledAssignment() throws Exception { @Test public void test150RoleEngineer() throws Exception { - final String TEST_NAME = "test150RoleEngineer"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -438,7 +418,7 @@ public void test150RoleEngineer() throws Exception { ObjectDeltaObject userOdo = createUserOdo(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); @@ -451,7 +431,7 @@ public void test150RoleEngineer() throws Exception { assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals(4, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -472,10 +452,8 @@ public void test150RoleEngineer() throws Exception { @Test public void test160AddRoleEngineer() throws Exception { - final String TEST_NAME = "test160AddRoleEngineer"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject user = userTypeJack.asPrismObject().clone(); @@ -491,12 +469,13 @@ public void test160AddRoleEngineer() throws Exception { AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); - EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, - false, userTypeJack, TEST_NAME, AssignmentOrigin.createNotVirtual(), task, result); + EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate( + assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, + getTestNameShort(), AssignmentOrigin.createNotVirtual(), task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); // THEN @@ -504,7 +483,7 @@ public void test160AddRoleEngineer() throws Exception { assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals("Wrong number of constructions", 4, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -538,16 +517,14 @@ public void test160AddRoleEngineer() throws Exception { /** * jack has assigned role Manager. - * + *

* However, condition in job metarole for Manager is such that it needs "management" * to be present in user/costCenter in order to be active. */ @Test public void test170RoleManagerChangeCostCenter() throws Exception { - final String TEST_NAME = "test170RoleManagerChangeCostCenter"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject user = userTypeJack.asPrismObject().clone(); @@ -559,17 +536,18 @@ public void test170RoleManagerChangeCostCenter() throws Exception { ObjectDelta userDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, USER_JACK_OID, - UserType.F_COST_CENTER, "management"); + UserType.F_COST_CENTER, "management"); ObjectDeltaObject userOdo = createUserOdo(user, userDelta); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); - EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, - false, userTypeJack, TEST_NAME, AssignmentOrigin.createInObject(), task, result); + EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate( + assignmentIdi, PlusMinusZero.ZERO, false, userTypeJack, + getTestNameShort(), AssignmentOrigin.createInObject(), task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); // THEN @@ -578,7 +556,7 @@ public void test170RoleManagerChangeCostCenter() throws Exception { TestUtil.assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals(4, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -599,18 +577,16 @@ public void test170RoleManagerChangeCostCenter() throws Exception { /** * jack has assigned role Manager. - * + *

* However, condition in job metarole for Manager is such that it needs "management" * to be present in user/costCenter in order to be active. - * + *

* In this test we remove the value of "management" from jack. */ @Test public void test180RoleManagerRemoveCostCenter() throws Exception { - final String TEST_NAME = "test180RoleManagerRemoveCostCenter"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject user = userTypeJack.asPrismObject().clone(); @@ -623,17 +599,17 @@ public void test180RoleManagerRemoveCostCenter() throws Exception { ObjectDelta userDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, USER_JACK_OID, - UserType.F_COST_CENTER); + UserType.F_COST_CENTER); ObjectDeltaObject userOdo = createUserOdo(user, userDelta); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(userOdo); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); EvaluatedAssignmentImpl evaluatedAssignment = assignmentEvaluator.evaluate(assignmentIdi, PlusMinusZero.ZERO, - false, userTypeJack, TEST_NAME, AssignmentOrigin.createInObject(), task, result); + false, userTypeJack, getTestNameShort(), AssignmentOrigin.createInObject(), task, result); evaluatedAssignment.evaluateConstructions(userOdo, task, result); // THEN @@ -642,7 +618,7 @@ public void test180RoleManagerRemoveCostCenter() throws Exception { TestUtil.assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals(4, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -667,10 +643,8 @@ public void test180RoleManagerRemoveCostCenter() throws Exception { @Test(enabled = false) public void test200DisableEngineerEmployeeInducement() throws Exception { - final String TEST_NAME = "test200DisableEngineerEmployeeInducement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // disable Engineer->Employee inducement @@ -687,7 +661,7 @@ public void test200DisableEngineerEmployeeInducement() throws Exception { ObjectDeltaObject userOdo = createUserOdo(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); @@ -701,17 +675,15 @@ public void test200DisableEngineerEmployeeInducement() throws Exception { TestUtil.assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); // TODO } @Test(enabled = false) public void test299ReenableEngineerEmployeeInducement() throws Exception { - final String TEST_NAME = "test299ReenableEngineerEmployeeInducement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // disable Engineer->Employee inducement @@ -728,17 +700,15 @@ public void test299ReenableEngineerEmployeeInducement() throws Exception { @Test public void test300DisableRoleEmployee() throws Exception { - final String TEST_NAME = "test300DisableRoleEmployee"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // disable role Employee ObjectDelta disableEmployeeDelta = prismContext.deltaFor(RoleType.class) .item(ACTIVATION_ADMINISTRATIVE_STATUS_PATH).replace(ActivationStatusType.DISABLED) .asObjectDelta(ROLE_CORP_EMPLOYEE_OID); - modelService.executeChanges(Collections.>singletonList(disableEmployeeDelta), + modelService.executeChanges(Collections.singletonList(disableEmployeeDelta), null, task, result); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(); @@ -748,7 +718,7 @@ public void test300DisableRoleEmployee() throws Exception { ObjectDeltaObject userOdo = createUserOdo(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); @@ -762,7 +732,7 @@ public void test300DisableRoleEmployee() throws Exception { TestUtil.assertSuccess(result); assertNotNull(evaluatedAssignment); - display("Evaluated assignment",evaluatedAssignment.debugDump()); + display("Evaluated assignment", evaluatedAssignment.debugDump()); assertEquals(2, evaluatedAssignment.getConstructionTriple().size()); PrismAsserts.assertParentConsistency(userTypeJack.asPrismObject()); @@ -783,17 +753,15 @@ public void test300DisableRoleEmployee() throws Exception { @Test public void test310DisableRoleEngineer() throws Exception { - final String TEST_NAME = "test310DisableRoleEngineer"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // disable role Engineer ObjectDelta disableEngineerDelta = prismContext.deltaFor(RoleType.class) .item(ACTIVATION_ADMINISTRATIVE_STATUS_PATH).replace(ActivationStatusType.DISABLED) .asObjectDelta(ROLE_CORP_ENGINEER_OID); - modelService.executeChanges(Collections.>singletonList(disableEngineerDelta), + modelService.executeChanges(Collections.singletonList(disableEngineerDelta), null, task, result); AssignmentEvaluator assignmentEvaluator = createAssignmentEvaluator(); @@ -803,7 +771,7 @@ public void test310DisableRoleEngineer() throws Exception { ObjectDeltaObject userOdo = createUserOdo(userTypeJack.asPrismObject()); - ItemDeltaItem,PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); + ItemDeltaItem, PrismContainerDefinition> assignmentIdi = createAssignmentIdi(assignmentType); // WHEN when(); @@ -843,10 +811,8 @@ public void test310DisableRoleEngineer() throws Exception { // MID-4251 @Test public void test400UserFred() throws Exception { - final String TEST_NAME = "test400UserFred"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentEvaluator.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); String pastTime = XmlTypeConverter.fromNow(createDuration("-P3D")).toString(); @@ -883,19 +849,20 @@ public void test400UserFred() throws Exception { } protected void assertNoConstruction(EvaluatedAssignmentImpl evaluatedAssignment, PlusMinusZero constructionSet, String attributeName) { - Collection> constructions = evaluatedAssignment.getConstructionSet(constructionSet); - for (Construction construction : constructions) { - PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> mapping = construction.getAttributeMapping(new QName(MidPointConstants.NS_RI, attributeName)); - assertNull("Unexpected mapping for " + attributeName, mapping); - } + Collection> constructions = evaluatedAssignment.getConstructionSet(constructionSet); + for (Construction construction : constructions) { + PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> mapping = + construction.getAttributeMapping(new QName(MidPointConstants.NS_RI, attributeName)); + assertNull("Unexpected mapping for " + attributeName, mapping); } - + } protected void assertConstruction(EvaluatedAssignmentImpl evaluatedAssignment, PlusMinusZero constructionSet, String attributeName, PlusMinusZero attributeSet, String... expectedValues) { Collection> constructions = evaluatedAssignment.getConstructionSet(constructionSet); Set realValues = new HashSet<>(); for (Construction construction : constructions) { - PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> mapping = construction.getAttributeMapping(new QName(MidPointConstants.NS_RI, attributeName)); + PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> mapping = + construction.getAttributeMapping(new QName(MidPointConstants.NS_RI, attributeName)); if (mapping != null && mapping.getOutputTriple() != null) { Collection> valsInMapping = mapping.getOutputTriple().getSet(attributeSet); if (valsInMapping != null) { @@ -910,13 +877,13 @@ protected void assertConstruction(EvaluatedAssignmentImpl evaluatedAss AssertJUnit.assertEquals("Wrong values", new HashSet<>(Arrays.asList(expectedValues)), realValues); } - protected AssignmentEvaluator createAssignmentEvaluator() throws ObjectNotFoundException, SchemaException { + protected AssignmentEvaluator createAssignmentEvaluator() throws SchemaException { PrismObject userJack = userTypeJack.asPrismObject(); ObjectDeltaObject focusOdo = createUserOdo(userJack); return createAssignmentEvaluator(focusOdo); } - protected AssignmentEvaluator createAssignmentEvaluator(ObjectDeltaObject focusOdo) throws ObjectNotFoundException, SchemaException { + protected AssignmentEvaluator createAssignmentEvaluator(ObjectDeltaObject focusOdo) { LensContext lensContext = createLensContext(UserType.class); LensFocusContext focusContext = lensContext.getOrCreateFocusContext(); focusContext.setObjectOld(focusOdo.getOldObject()); @@ -949,7 +916,7 @@ private ObjectDeltaObject createUserOdo(PrismObject user, Ob return userOdo; } - private ItemDeltaItem,PrismContainerDefinition> createAssignmentIdi(AssignmentType assignmentType) throws SchemaException { + private ItemDeltaItem, PrismContainerDefinition> createAssignmentIdi(AssignmentType assignmentType) throws SchemaException { return new ItemDeltaItem<>(LensUtil.createAssignmentSingleValueContainer(assignmentType), getAssignmentDefinition()); } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java index 439108cd638..3121aac06fb 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignedMappings.java @@ -6,8 +6,11 @@ */ package com.evolveum.midpoint.model.impl.lens; -import com.evolveum.midpoint.common.Clock; -import com.evolveum.midpoint.model.impl.lens.projector.focus.AssignmentProcessor; +import java.io.File; +import javax.xml.bind.JAXBElement; + +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.schema.SchemaConstantsGenerated; @@ -18,15 +21,7 @@ import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; -import org.springframework.beans.factory.annotation.Autowired; -import org.testng.annotations.Test; -import javax.xml.bind.JAXBElement; -import java.io.File; - -/** - * - */ public class TestAssignedMappings extends AbstractLensTest { protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "lens/focusMappings"); @@ -72,17 +67,12 @@ public class TestAssignedMappings extends AbstractLensTest { private static final TestResource USER_ADAM = new TestResource(TEST_DIR, "user-adam.xml", "cf10f112-a731-45cd-8dfb-1b3fe9375c14"); private static final TestResource USER_BENJAMIN = new TestResource(TEST_DIR, "user-benjamin.xml", "2e1a427c-d6a7-4783-90ec-9dc0ebc98630"); - //private static final TestResource ROLE_ORGANIZER = new TestResource(TEST_DIR, "role-organizer.xml", "7d31a3c2-cecf-4e3d-8740-988b37848a7c"); - private static final TestResource USER_FRODO = new TestResource(TEST_DIR, "user-frodo.xml", "786919b7-23c9-4a38-90e7-5a1efd0ab853"); private static final TestResource ROLE_BEARABLE = new TestResource(TEST_DIR, "metarole-bearable.xml", "2421b2c5-8563-4ba7-9a87-f9ef4b169620"); private static final TestResource SERVICE_RING = new TestResource(TEST_DIR, "service-ring.xml", "7540cf28-a143-4eea-9379-75cae5d212cb"); private static final TestResource SERVICE_STING = new TestResource(TEST_DIR, "service-sting.xml", "f8b109bf-d393-47b9-8eec-41d74e39a992"); private static final TestResource ROLE_PROPAGATOR = new TestResource(TEST_DIR, "role-propagator.xml", "8e56a98a-bcb9-4178-94f2-5488da473132"); - @Autowired private AssignmentProcessor assignmentProcessor; - @Autowired private Clock clock; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -140,10 +130,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100AssignSimpleToJim() throws Exception { - final String TEST_NAME = "test100AssignSimpleToJim"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -187,10 +174,7 @@ public void test100AssignSimpleToJim() throws Exception { */ @Test public void test110AssignRingToFrodo() throws Exception { - final String TEST_NAME = "test110AssignRingToFrodo"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -237,10 +221,7 @@ public void test110AssignRingToFrodo() throws Exception { */ @Test public void test120AssignStingToFrodo() throws Exception { - final String TEST_NAME = "test120AssignStingToFrodo"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -286,10 +267,7 @@ public void test120AssignStingToFrodo() throws Exception { */ @Test public void test130UnassignRingFromFrodo() throws Exception { - final String TEST_NAME = "test130UnassignRingFromFrodo"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -342,10 +320,7 @@ public void test130UnassignRingFromFrodo() throws Exception { */ @Test public void test200AssignRolesToAdam() throws Exception { - final String TEST_NAME = "test200AssignRolesToAdam"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -400,10 +375,7 @@ public void test200AssignRolesToAdam() throws Exception { */ @Test public void test210AssignRolesToBenjamin() throws Exception { - final String TEST_NAME = "test210AssignRolesToBenjamin"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -424,7 +396,6 @@ public void test210AssignRolesToBenjamin() throws Exception { // THEN assertSuccess(result); PrismObject benjaminAfter = getUserFromRepo(USER_BENJAMIN.oid); - UserType benjaminAfterBean = benjaminAfter.asObjectable(); new UserAsserter<>(benjaminAfter) .display() .assertExtensionValue("p111a", "null:mmr1.1.1") @@ -485,10 +456,7 @@ public void test210AssignRolesToBenjamin() throws Exception { */ @Test public void test220AdamConditionFalseToTrue() throws Exception { - final String TEST_NAME = "test220AdamConditionFalseToTrue"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -503,7 +471,6 @@ public void test220AdamConditionFalseToTrue() throws Exception { // THEN assertSuccess(result); PrismObject adamAfter = getUserFromRepo(USER_ADAM.oid); - UserType adamAfterBean = adamAfter.asObjectable(); new UserAsserter<>(adamAfter) .display() .assertExtensionValue("p111a", "null:mmr1.1.1") @@ -564,10 +531,7 @@ public void test220AdamConditionFalseToTrue() throws Exception { */ @Test public void test230BenjaminConditionTrueToFalse() throws Exception { - final String TEST_NAME = "test230BenjaminConditionTrueToFalse"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -582,7 +546,6 @@ public void test230BenjaminConditionTrueToFalse() throws Exception { // THEN assertSuccess(result); PrismObject benjaminAfter = getUserFromRepo(USER_BENJAMIN.oid); - UserType benjaminAfterBean = benjaminAfter.asObjectable(); new UserAsserter<>(benjaminAfter) .display() .assertExtensionValue("p111a", "null:mmr1.1.1") @@ -598,10 +561,7 @@ public void test230BenjaminConditionTrueToFalse() throws Exception { */ @Test public void test280UnassignRolesFromAdam() throws Exception { - final String TEST_NAME = "test280UnassignRolesFromAdam"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -616,7 +576,6 @@ public void test280UnassignRolesFromAdam() throws Exception { // THEN assertSuccess(result); PrismObject adamAfter = getUserFromRepo(USER_ADAM.oid); - UserType adamAfterBean = adamAfter.asObjectable(); new UserAsserter<>(adamAfter) .display() .assertExtensionItems(0) @@ -628,10 +587,7 @@ public void test280UnassignRolesFromAdam() throws Exception { */ @Test public void test290UnassignRolesFromBenjamin() throws Exception { - final String TEST_NAME = "test290UnassignRolesFromBenjamin"; - // GIVEN - TestAssignedMappings.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -646,7 +602,6 @@ public void test290UnassignRolesFromBenjamin() throws Exception { // THEN assertSuccess(result); PrismObject benjaminAfter = getUserFromRepo(USER_BENJAMIN.oid); - UserType benjaminAfterBean = benjaminAfter.asObjectable(); new UserAsserter<>(benjaminAfter) .display() .assertExtensionItems(0) @@ -689,7 +644,7 @@ private AssignmentType createRoleAssignmentDisabled(TestResource role) { // @Test // public void test150UnassignOrganizerFromAdam() throws Exception { // // GIVEN -// Task task = createTask(TestAssignedMappings.class.getName() + "." + TEST_NAME); +// Task task = getTestTask(); // setModelLoggingTracing(task); // OperationResult result = task.getResult(); // diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor.java index 8796cdf2065..07de2079881 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAssignmentProcessor.java @@ -6,6 +6,17 @@ */ package com.evolveum.midpoint.model.impl.lens; +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.prism.delta.PlusMinusZero.*; + +import java.util.*; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.springframework.beans.factory.annotation.Autowired; +import org.testng.annotations.Test; + import com.evolveum.midpoint.common.Clock; import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRule; import com.evolveum.midpoint.model.common.mapping.MappingImpl; @@ -15,7 +26,6 @@ import com.evolveum.midpoint.prism.PrismPropertyDefinition; import com.evolveum.midpoint.prism.PrismPropertyValue; import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.schema.constants.ObjectTypes; @@ -26,34 +36,15 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.testng.annotations.Test; - -import javax.xml.bind.JAXBException; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; - -import java.util.*; - -import static com.evolveum.midpoint.prism.delta.PlusMinusZero.MINUS; -import static com.evolveum.midpoint.prism.delta.PlusMinusZero.PLUS; -import static com.evolveum.midpoint.prism.delta.PlusMinusZero.ZERO; -import static org.testng.AssertJUnit.*; - -/** - * @author semancik - */ public class TestAssignmentProcessor extends AbstractLensTest { - private static final ItemPath ATTRIBUTES_PARENT_PATH = ShadowType.F_ATTRIBUTES; - @Autowired private AssignmentProcessor assignmentProcessor; @Autowired private Clock clock; - public TestAssignmentProcessor() throws JAXBException { + public TestAssignmentProcessor() { super(); } @@ -70,10 +61,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test001OutboundEmpty() throws Exception { - final String TEST_NAME = "test001OutboundEmpty"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -85,7 +74,6 @@ public void test001OutboundEmpty() throws Exception { // THEN display("outbound processor result", result); -// assertSuccess("Outbound processor failed (result)", result); assertNull(context.getFocusContext().getPrimaryDelta()); assertNull(context.getFocusContext().getSecondaryDelta()); @@ -94,10 +82,8 @@ public void test001OutboundEmpty() throws Exception { @Test public void test002ModifyUser() throws Exception { - final String TEST_NAME = "test002ModifyUser"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -136,7 +122,7 @@ public void test002ModifyUser() throws Exception { assignmentProcessor.processAssignmentsAccountValues(accContext, result); PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = - accContext.getConstructionDeltaSetTriple(); + accContext.getConstructionDeltaSetTriple(); display("accountConstructionDeltaSetTriple", accountConstructionDeltaSetTriple); PrismAsserts.assertTripleNoMinus(accountConstructionDeltaSetTriple); @@ -156,10 +142,8 @@ public void test002ModifyUser() throws Exception { @Test public void test011AddAssignmentAddAccountDirect() throws Exception { - final String TEST_NAME = "test011AddAssignmentAddAccountDirect"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -197,10 +181,8 @@ public void test011AddAssignmentAddAccountDirect() throws Exception { @Test public void test012AddAssignmentAddAccountDirectAssignmentWithAttrs() throws Exception { - final String TEST_NAME = "test012AddAssignmentAddAccountDirectAssignmentWithAttrs"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -240,7 +222,7 @@ public void test012AddAssignmentAddAccountDirectAssignmentWithAttrs() throws Exc assignmentProcessor.processAssignmentsAccountValues(accContext, result); PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = - accContext.getConstructionDeltaSetTriple(); + accContext.getConstructionDeltaSetTriple(); PrismAsserts.assertTripleNoMinus(accountConstructionDeltaSetTriple); PrismAsserts.assertTripleNoZero(accountConstructionDeltaSetTriple); @@ -267,9 +249,8 @@ public void test012AddAssignmentAddAccountDirectAssignmentWithAttrs() throws Exc @Test public void test021AddAssignmentModifyAccountAssignment() throws Exception { - final String TEST_NAME = "test021AddAssignmentModifyAccountAssignment"; // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -308,7 +289,7 @@ public void test021AddAssignmentModifyAccountAssignment() throws Exception { assignmentProcessor.processAssignmentsAccountValues(accContext, result); PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = - accContext.getConstructionDeltaSetTriple(); + accContext.getConstructionDeltaSetTriple(); PrismAsserts.assertTripleNoMinus(accountConstructionDeltaSetTriple); @@ -360,10 +341,8 @@ public void test021AddAssignmentModifyAccountAssignment() throws Exception { @Test public void test031DeleteAssignmentModifyAccount() throws Exception { - final String TEST_NAME = "test031DeleteAssignmentModifyAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -406,9 +385,8 @@ public void test031DeleteAssignmentModifyAccount() throws Exception { assignmentProcessor.processAssignmentsAccountValues(accContext, result); - PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple = - accContext.getConstructionDeltaSetTriple(); + accContext.getConstructionDeltaSetTriple(); PrismAsserts.assertTripleNoPlus(accountConstructionDeltaSetTriple); @@ -444,58 +422,55 @@ public void test031DeleteAssignmentModifyAccount() throws Exception { } @Test - public void test032ModifyUserLegalizeAccount() throws Exception { - final String TEST_NAME = "test032ModifyUserLegalizeAccount"; - + public void test032ModifyUserLegalizeAccount() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); - OperationResult result = task.getResult(); + Task task = getTestTask(); + OperationResult result = task.getResult(); - repoAddObjectFromFile(USER_LARGO_FILE, result); + repoAddObjectFromFile(USER_LARGO_FILE, result); - LensContext context = createUserLensContext(); - fillContextWithUser(context, USER_LARGO_OID, result); - fillContextWithAccountFromFile(context, ACCOUNT_SHADOW_ELAINE_DUMMY_FILE, task, result); - context.recompute(); + LensContext context = createUserLensContext(); + fillContextWithUser(context, USER_LARGO_OID, result); + fillContextWithAccountFromFile(context, ACCOUNT_SHADOW_ELAINE_DUMMY_FILE, task, result); + context.recompute(); - ProjectionPolicyType accountSynchronizationSettings = new ProjectionPolicyType(); - accountSynchronizationSettings.setLegalize(Boolean.TRUE); - accountSynchronizationSettings.setAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE); - context.setAccountSynchronizationSettings(accountSynchronizationSettings); + ProjectionPolicyType accountSynchronizationSettings = new ProjectionPolicyType(); + accountSynchronizationSettings.setLegalize(Boolean.TRUE); + accountSynchronizationSettings.setAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE); + context.setAccountSynchronizationSettings(accountSynchronizationSettings); - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_OID, AssignmentPolicyEnforcementType.POSITIVE, true); + assumeResourceAssigmentPolicy(RESOURCE_DUMMY_OID, AssignmentPolicyEnforcementType.POSITIVE, true); - display("Input context", context); + display("Input context", context); - assertFocusModificationSanity(context); + assertFocusModificationSanity(context); - // WHEN - assignmentProcessor.processAssignments(context, getNow(), task, result); + // WHEN + assignmentProcessor.processAssignments(context, getNow(), task, result); - context.recompute(); - // THEN - display("Output context", context); - display("outbound processor result", result); + context.recompute(); + // THEN + display("Output context", context); + display("outbound processor result", result); - assertNotNull("Expected assigment change in secondary user changes, but it does not exist.", context.getFocusContext().getSecondaryDelta()); - assertEquals("Unexpected number of secundary changes. ", 1, context.getFocusContext().getSecondaryDelta().getModifications().size()); - assertNotNull("Expected assigment delta in secondary changes, but it does not exist.", - ItemDeltaCollectionsUtil.findContainerDelta(context.getFocusContext().getSecondaryDelta().getModifications(), - UserType.F_ASSIGNMENT)); - assertFalse("No account changes", context.getProjectionContexts().isEmpty()); + assertNotNull("Expected assigment change in secondary user changes, but it does not exist.", context.getFocusContext().getSecondaryDelta()); + assertEquals("Unexpected number of secundary changes. ", 1, context.getFocusContext().getSecondaryDelta().getModifications().size()); + assertNotNull("Expected assigment delta in secondary changes, but it does not exist.", + ItemDeltaCollectionsUtil.findContainerDelta(context.getFocusContext().getSecondaryDelta().getModifications(), + UserType.F_ASSIGNMENT)); + assertFalse("No account changes", context.getProjectionContexts().isEmpty()); - LensProjectionContext accContext = context.getProjectionContexts().iterator().next(); + LensProjectionContext accContext = context.getProjectionContexts().iterator().next(); - assertNoDecision(accContext); - assertLegal(accContext); + assertNoDecision(accContext); + assertLegal(accContext); - } + } @Test public void test100AddAssignmentWithConditionalMetarole() throws Exception { - final String TEST_NAME = "test100AddAssignmentWithConditionalMetarole"; // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -557,9 +532,8 @@ public void test100AddAssignmentWithConditionalMetarole() throws Exception { */ @Test public void test102EnableConditionalMetarole() throws Exception { - final String TEST_NAME = "test102EnableConditionalMetarole"; // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -633,16 +607,15 @@ public void test102EnableConditionalMetarole() throws Exception { * any similar tests here; use TestPolicyRules instead. It contains better 'assume' methods for policies. * TODO move these ones as well * =============================================================================================== - * + *

* Checking approval policy rules. * Visitor has a generic metarole that has associated policy rule (approve-any-corp-role). * Generic metarole also induces metarole-sod-notifications that has "notify-exclusion-violations" rule. */ @Test public void test200AssignVisitor() throws Exception { - final String TEST_NAME = "test200AssignVisitor"; // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -689,14 +662,13 @@ public void test200AssignVisitor() throws Exception { * Engineer has a generic metarole that provides these policy rules: approve-any-corp-rule, notify-exclusion-violations. * However, it induces an Employee role that has also this generic metarole. Moreover, it has "employee-excludes-contractor" * rule. - * + *

* First occurrence of the approval rule should have a trigger. Second one should be without a trigger. */ @Test public void test210AssignEngineer() throws Exception { - final String TEST_NAME = "test210AssignEngineer"; // GIVEN - Task task = taskManager.createTaskInstance(TestAssignmentProcessor.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -762,26 +734,26 @@ private Set getAttributeValues(Collection void assertPlusAttributeValues(Construction accountConstruction, QName attrName, T... expectedValue) { PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> vc = accountConstruction.getAttributeMapping(attrName); - assertNotNull("No value construction for attribute "+attrName+" in plus set", vc); + assertNotNull("No value construction for attribute " + attrName + " in plus set", vc); PrismValueDeltaSetTriple> triple = vc.getOutputTriple(); - Collection actual = getMultiValueFromDeltaSetTriple(triple, triple.getPlusSet()); - TestUtil.assertSetEquals("Attribute "+attrName+" value in plus set", actual, expectedValue); + Collection actual = getMultiValueFromDeltaSetTriple(triple.getPlusSet()); + TestUtil.assertSetEquals("Attribute " + attrName + " value in plus set", actual, expectedValue); } private void assertZeroAttributeValues(Construction accountConstruction, QName attrName, T... expectedValue) { PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> vc = accountConstruction.getAttributeMapping(attrName); - assertNotNull("No value construction for attribute "+attrName+" in zero set", vc); + assertNotNull("No value construction for attribute " + attrName + " in zero set", vc); PrismValueDeltaSetTriple> triple = vc.getOutputTriple(); - Collection actual = getMultiValueFromDeltaSetTriple(triple, triple.getZeroSet()); - TestUtil.assertSetEquals("Attribute "+attrName+" value in zero set", actual, expectedValue); + Collection actual = getMultiValueFromDeltaSetTriple(triple.getZeroSet()); + TestUtil.assertSetEquals("Attribute " + attrName + " value in zero set", actual, expectedValue); } private void assertMinusAttributeValues(Construction accountConstruction, QName attrName, T... expectedValue) { PrismValueDeltaSetTripleProducer, ? extends PrismPropertyDefinition> vc = accountConstruction.getAttributeMapping(attrName); - assertNotNull("No value construction for attribute "+attrName+" in minus set", vc); + assertNotNull("No value construction for attribute " + attrName + " in minus set", vc); PrismValueDeltaSetTriple> triple = vc.getOutputTriple(); - Collection actual = getMultiValueFromDeltaSetTriple(triple, triple.getMinusSet()); - TestUtil.assertSetEquals("Attribute "+attrName+" value in minus set", actual, expectedValue); + Collection actual = getMultiValueFromDeltaSetTriple(triple.getMinusSet()); + TestUtil.assertSetEquals("Attribute " + attrName + " value in minus set", actual, expectedValue); } private void assertNoPlusAttributeValues(Construction accountConstruction, QName attrName) { @@ -802,25 +774,24 @@ private void assertNoMinusAttributeValues(Construction accountConstruction, QNam PrismAsserts.assertTripleNoMinus(triple); } - private Object getSingleValueFromDeltaSetTriple(PrismValueDeltaSetTriple> triple, - Collection> set) { - Collection values = getMultiValueFromDeltaSetTriple(triple,set); - assertEquals(1,values.size()); + private Object getSingleValueFromDeltaSetTriple(Collection> set) { + Collection values = getMultiValueFromDeltaSetTriple(set); + assertEquals(1, values.size()); return values.iterator().next(); } - private Collection getMultiValueFromDeltaSetTriple(PrismValueDeltaSetTriple> triple, + private Collection getMultiValueFromDeltaSetTriple( Collection> set) { Collection vals = new ArrayList<>(set.size()); - for (PrismPropertyValue pval: set) { - vals.add((T)pval.getValue()); + for (PrismPropertyValue pval : set) { + vals.add((T) pval.getValue()); } return vals; } - private void assertSetSize(String setName, Collection> set, - int expectedSize) { - assertEquals("Unexpected number of value in "+setName+" set", expectedSize, set.size()); + private void assertSetSize( + String setName, Collection> set, int expectedSize) { + assertEquals("Unexpected number of value in " + setName + " set", expectedSize, set.size()); } private Construction getZeroAccountConstruction( @@ -829,8 +800,8 @@ private Construction getZeroAccountConstruction( } private Construction getZeroAccountConstruction( - PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple, - String description) { + PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple, + String description) { Collection> set = accountConstructionDeltaSetTriple.getZeroSet(); return getAccountConstruction(accountConstructionDeltaSetTriple, description, set, "zero"); } @@ -861,10 +832,10 @@ private Construction getMinusAccountConstruction( private Construction getAccountConstruction(PrismValueDeltaSetTriple> accountConstructionDeltaSetTriple, String description, Collection> set, String setName) { - for (PrismPropertyValue constructionPVal: set) { + for (PrismPropertyValue constructionPVal : set) { Construction accountConstruction = constructionPVal.getValue(); if (description == null || description.equals(accountConstruction.getDescription())) { - assertNotNull("Null accountConstruction in "+setName+" set (description: '"+description+"')", accountConstruction); + assertNotNull("Null accountConstruction in " + setName + " set (description: '" + description + "')", accountConstruction); return accountConstruction; } } @@ -872,15 +843,18 @@ private Construction getAccountConstruction(PrismValueDeltaSetTriple context2 = LensContext.fromLensContextType( + unmarshalledContainer, context.getPrismContext(), provisioningService, task, result); display("Context after deserialization", context); @@ -119,19 +99,18 @@ public void test010SerializeAddUserBarbossa() throws Exception { then(); assertEquals("Secondary deltas are not preserved - their number differs", context.getFocusContext().getSecondaryDeltas().size(), context2.getFocusContext().getSecondaryDeltas().size()); for (int i = 0; i < context.getFocusContext().getSecondaryDeltas().size(); i++) { - assertTrue("Secondary delta #" + i + " is not preserved correctly, " - + "expected:\n" + context.getFocusContext().getSecondaryDelta(i).debugDump() - + "but was\n" + context2.getFocusContext().getSecondaryDelta(i).debugDump(), - context.getFocusContext().getSecondaryDelta(i).equals(context2.getFocusContext().getSecondaryDelta(i))); + assertEquals( + "Secondary delta #" + i + " is not preserved correctly, " + + "expected:\n" + context.getFocusContext().getSecondaryDelta(i).debugDump() + + "but was\n" + context2.getFocusContext().getSecondaryDelta(i).debugDump(), + context2.getFocusContext().getSecondaryDelta(i), + context.getFocusContext().getSecondaryDelta(i)); } } @Test public void test020AssignAccountToJackSync() throws Exception { - final String TEST_NAME = "test020AssignAccountToJackSync"; - try { - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -172,11 +151,8 @@ public void test020AssignAccountToJackSync() throws Exception { @Test public void test030AssignAccountToJackAsyncNoserialize() throws Exception { - final String TEST_NAME = "test030AssignAccountToJackAsyncNoserialize"; try { - - assignAccountToJackAsync(TEST_NAME, false); - + assignAccountToJackAsync(false); } finally { displayCleanup(); mockClockworkHook.reset(); @@ -187,11 +163,8 @@ public void test030AssignAccountToJackAsyncNoserialize() throws Exception { @Test public void test031AssignAccountToJackAsyncSerialize() throws Exception { - final String TEST_NAME = "test031AssignAccountToJackAsyncSerialize"; try { - - assignAccountToJackAsync(TEST_NAME, true); - + assignAccountToJackAsync(true); } finally { displayCleanup(); mockClockworkHook.reset(); @@ -201,13 +174,12 @@ public void test031AssignAccountToJackAsyncSerialize() throws Exception { } /** - * User barbossa has a direct account assignment. This assignment has an expression for enabledisable flag. + * User barbossa has a direct account assignment. + * This assignment has an expression for enabledisable flag. * Let's disable user, the account should be disabled as well. */ @Test public void test053ModifyUserBarbossaDisable() throws Exception { - final String TEST_NAME = "test053ModifyUserBarbossaDisable"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -215,7 +187,8 @@ public void test053ModifyUserBarbossaDisable() throws Exception { LensContext context = createUserLensContext(); fillContextWithUser(context, USER_BARBOSSA_OID, result); fillContextWithAccount(context, ACCOUNT_HBARBOSSA_DUMMY_OID, task, result); - addModificationToContextReplaceUserProperty(context, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ActivationStatusType.DISABLED); + addModificationToContextReplaceUserProperty( + context, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, ActivationStatusType.DISABLED); context.recompute(); display("Input context", context); @@ -230,7 +203,7 @@ public void test053ModifyUserBarbossaDisable() throws Exception { then(); display("Output context", context); - assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); + assertSame(context.getFocusContext().getPrimaryDelta().getChangeType(), ChangeType.MODIFY); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.DISABLED); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -239,7 +212,7 @@ public void test053ModifyUserBarbossaDisable() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); @@ -262,8 +235,7 @@ public void test053ModifyUserBarbossaDisable() throws Exception { } - private void assignAccountToJackAsync(String testName, boolean serialize) throws Exception { - + private void assignAccountToJackAsync(boolean serialize) throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -272,8 +244,6 @@ private void assignAccountToJackAsync(String testName, boolean serialize) throws LensContext context = createJackAssignAccountContext(result); -// display("Input context", context); - assertFocusModificationSanity(context); mockClockworkHook.reset(); mockClockworkHook.setRecord(true); @@ -281,28 +251,31 @@ private void assignAccountToJackAsync(String testName, boolean serialize) throws rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); // WHEN - when(testName); - while(context.getState() != ModelState.FINAL) { - - display("CLICK START: "+context.getState()); + when(); + while (context.getState() != ModelState.FINAL) { + display("CLICK START: " + context.getState()); HookOperationMode mode = clockwork.click(context, task, result); - display("CLICK END: "+context.getState()); + display("CLICK END: " + context.getState()); - assertTrue("Unexpected INITIAL state of the context", context.getState() != ModelState.INITIAL); - assertEquals("Wrong mode after click in "+context.getState(), HookOperationMode.BACKGROUND, mode); + assertNotSame("Unexpected INITIAL state of the context", + context.getState(), ModelState.INITIAL); + assertEquals("Wrong mode after click in " + context.getState(), + HookOperationMode.BACKGROUND, mode); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); if (serialize) { - display("Context before serialization", context); LensContextType lensContextType = context.toLensContextType(); - String xml = prismContext.xmlSerializer().serializeRealValue(lensContextType, SchemaConstants.C_MODEL_CONTEXT); + String xml = prismContext.xmlSerializer().serializeRealValue( + lensContextType, SchemaConstants.C_MODEL_CONTEXT); display("Serialized form", xml); - LensContextType unmarshalledContainer = prismContext.parserFor(xml).xml().parseRealValue(LensContextType.class); - context = LensContext.fromLensContextType(unmarshalledContainer, context.getPrismContext(), provisioningService, task, result); + LensContextType unmarshalledContainer = + prismContext.parserFor(xml).xml().parseRealValue(LensContextType.class); + context = LensContext.fromLensContextType(unmarshalledContainer, + context.getPrismContext(), provisioningService, task, result); display("Context after deserialization", context.debugDump()); @@ -311,10 +284,8 @@ private void assignAccountToJackAsync(String testName, boolean serialize) throws } // THEN - then(testName); + then(); mockClockworkHook.setRecord(false); -// display("Output context", context); -// display("Hook contexts", mockClockworkHook); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); assertJackAssignAccountContext(context); @@ -322,10 +293,10 @@ private void assignAccountToJackAsync(String testName, boolean serialize) throws } private void assertJackAssignAccountContext(LensContext context) { - assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); + assertSame(context.getFocusContext().getPrimaryDelta().getChangeType(), ChangeType.MODIFY); if (context.getFocusContext().getSecondaryDelta() != null) { assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", - ActivationStatusType.ENABLED); + ActivationStatusType.ENABLED); } assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -339,7 +310,7 @@ private void assertJackAssignAccountContext(LensContext context) { assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta executedDelta = getExecutedDelta(accContext); - assertNotNull("No executed delta in "+accContext, executedDelta); + assertNotNull("No executed delta in " + accContext, executedDelta); assertEquals(ChangeType.ADD, executedDelta.getChangeType()); PrismAsserts.assertPropertyAdd(executedDelta, getIcfsNameAttributePath(), "jack"); PrismAsserts.assertPropertyAdd(executedDelta, getDummyResourceController().getAttributeFullnamePath(), "Jack Sparrow"); @@ -352,17 +323,19 @@ private ObjectDelta getExecutedDelta(LensProjectionContext ctx) { return null; } if (executedDeltas.size() > 1) { - AssertJUnit.fail("More than one executed delta in "+ctx); + AssertJUnit.fail("More than one executed delta in " + ctx); } return executedDeltas.get(0).getObjectDelta(); } - private void assertJackAccountShadow(LensContext context) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private void assertJackAccountShadow(LensContext context) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { Collection accountContexts = context.getProjectionContexts(); assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); String accountOid = accContext.getOid(); - assertNotNull("No OID in account context "+accContext); + assertNotNull("No OID in account context " + accContext, accountOid); PrismObject newAccount = getShadowModel(accountOid); assertEquals(DEFAULT_INTENT, newAccount.findProperty(ShadowType.F_INTENT).getRealValue()); @@ -376,14 +349,18 @@ private void assertJackAccountShadow(LensContext context) throws Objec assertEquals("Jack Sparrow", attributes.findProperty(new ItemName(ResourceTypeUtil.getResourceNamespace(getDummyResourceType()), "fullname")).getRealValue()); } - private LensContext createJackAssignAccountContext(OperationResult result) throws SchemaException, ObjectNotFoundException, IOException, JAXBException { + private LensContext createJackAssignAccountContext(OperationResult result) + throws SchemaException, ObjectNotFoundException, IOException, JAXBException { LensContext context = createUserLensContext(); fillContextWithUser(context, USER_JACK_OID, result); addFocusModificationToContext(context, REQ_USER_JACK_MODIFY_ADD_ASSIGNMENT_ACCOUNT_DUMMY); return context; } - private void unassignJackAccount() throws SchemaException, ObjectNotFoundException, IOException, JAXBException, PolicyViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException, PreconditionViolationException { + private void unassignJackAccount() + throws SchemaException, ObjectNotFoundException, IOException, JAXBException, + PolicyViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException, + CommunicationException, ConfigurationException, SecurityViolationException, PreconditionViolationException { Task task = taskManager.createTaskInstance(TestClockwork.class.getName() + ".unassignJackAccount"); LensContext context = createUserLensContext(); OperationResult result = task.getResult(); @@ -391,5 +368,4 @@ private void unassignJackAccount() throws SchemaException, ObjectNotFoundExcepti addFocusModificationToContext(context, REQ_USER_JACK_MODIFY_DELETE_ASSIGNMENT_ACCOUNT_DUMMY); clockwork.run(context, task, result); } - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestDependencies.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestDependencies.java index fe3f57430f6..1bf562d9138 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestDependencies.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestDependencies.java @@ -25,47 +25,25 @@ import com.evolveum.icf.dummy.resource.SchemaViolationException; import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; import com.evolveum.midpoint.model.impl.lens.projector.DependencyProcessor; -import com.evolveum.midpoint.model.impl.lens.projector.Projector; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.ResourceShadowDiscriminator; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.test.DummyResourceContoller; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestDependencies extends AbstractInternalModelIntegrationTest { public static final File TEST_DIR = new File("src/test/resources/lens/dependencies"); private static final File ACCOUNT_ELAINE_TEMPLATE_FILE = new File(TEST_DIR, "account-elaine-template.xml"); - @Autowired(required = true) - private Projector projector; - - @Autowired(required = true) + @Autowired private DependencyProcessor dependencyProcessor; - @Autowired(required = true) - private TaskManager taskManager; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -94,29 +72,27 @@ private void initDummy(String name, Task initTask, OperationResult initResult) t } private File getDummFile(String name) { - return new File(TEST_DIR, "resource-dummy-"+name+".xml"); + return new File(TEST_DIR, "resource-dummy-" + name + ".xml"); } private String getDummyOid(String name) { - return "14440000-0000-0000-000"+name+"-000000000000"; + return "14440000-0000-0000-000" + name + "-000000000000"; } private String getDummuAccountOid(String dummyName, String accountName) { - return "14440000-0000-0000-000"+dummyName+"-10000000000"+accountName; + return "14440000-0000-0000-000" + dummyName + "-10000000000" + accountName; } @Test public void test100SortToWavesIdependent() throws Exception { - final String TEST_NAME = "test100SortToWavesIdependent"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); LensContext context = createUserLensContext(); - LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); - LensProjectionContext accountContext = fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); + fillContextWithUser(context, USER_ELAINE_OID, result); + fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); fillContextWithDummyElaineAccount(context, "a", task, result); context.recompute(); @@ -135,16 +111,14 @@ public void test100SortToWavesIdependent() throws Exception { @Test public void test101SortToWavesAB() throws Exception { - final String TEST_NAME = "test101SortToWavesAB"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); LensContext context = createUserLensContext(); - LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); - LensProjectionContext accountContext = fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); + fillContextWithUser(context, USER_ELAINE_OID, result); + fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); fillContextWithDummyElaineAccount(context, "a", task, result); fillContextWithDummyElaineAccount(context, "b", task, result); @@ -165,16 +139,14 @@ public void test101SortToWavesAB() throws Exception { @Test public void test102SortToWavesABCD() throws Exception { - final String TEST_NAME = "test102SortToWavesABCD"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); LensContext context = createUserLensContext(); - LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); - LensProjectionContext accountContext = fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); + fillContextWithUser(context, USER_ELAINE_OID, result); + fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); fillContextWithDummyElaineAccount(context, "a", task, result); fillContextWithDummyElaineAccount(context, "b", task, result); fillContextWithDummyElaineAccount(context, "c", task, result); @@ -199,15 +171,13 @@ public void test102SortToWavesABCD() throws Exception { @Test public void test120SortToWavesBCUnsatisfied() throws Exception { - final String TEST_NAME = "test120SortToWavesBCUnsatisfied"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); LensContext context = createUserLensContext(); - LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); + fillContextWithUser(context, USER_ELAINE_OID, result); fillContextWithDummyElaineAccount(context, "b", task, result); fillContextWithDummyElaineAccount(context, "c", task, result); @@ -226,13 +196,10 @@ public void test120SortToWavesBCUnsatisfied() throws Exception { } } - @Test public void test151SortToWavesPR() throws Exception { - final String TEST_NAME = "test151SortToWavesPR"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); @@ -262,10 +229,8 @@ public void test151SortToWavesPR() throws Exception { */ @Test public void test152SortToWavesRP() throws Exception { - final String TEST_NAME = "test152SortToWavesRP"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); @@ -291,15 +256,13 @@ public void test152SortToWavesRP() throws Exception { @Test public void test200SortToWavesIdependentDeprovision() throws Exception { - final String TEST_NAME = "test200SortToWavesIdependentDeprovision"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); LensContext context = createUserLensContext(); - LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); + fillContextWithUser(context, USER_ELAINE_OID, result); LensProjectionContext accountContext = fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); setDelete(accountContext); setDelete(fillContextWithDummyElaineAccount(context, "a", task, result)); @@ -320,15 +283,13 @@ public void test200SortToWavesIdependentDeprovision() throws Exception { @Test public void test201SortToWavesABDeprovision() throws Exception { - final String TEST_NAME = "test201SortToWavesABDeprovision"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); LensContext context = createUserLensContext(); - LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); + fillContextWithUser(context, USER_ELAINE_OID, result); LensProjectionContext accountContext = fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); setDelete(accountContext); setDelete(fillContextWithDummyElaineAccount(context, "a", task, result)); @@ -351,15 +312,13 @@ public void test201SortToWavesABDeprovision() throws Exception { @Test public void test202SortToWavesABCDDeprovision() throws Exception { - final String TEST_NAME = "test202SortToWavesABCDDeprovision"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); LensContext context = createUserLensContext(); - LensFocusContext focusContext = fillContextWithUser(context, USER_ELAINE_OID, result); + fillContextWithUser(context, USER_ELAINE_OID, result); LensProjectionContext accountContext = fillContextWithAccount(context, ACCOUNT_SHADOW_ELAINE_DUMMY_OID, task, result); setDelete(accountContext); setDelete(fillContextWithDummyElaineAccount(context, "a", task, result)); @@ -392,10 +351,8 @@ private void setDelete(LensProjectionContext accountContext) { @Test public void test300SortToWavesXYZCircular() throws Exception { - final String TEST_NAME = "test300SortToWavesXYZCircular"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDependencies.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); @@ -424,7 +381,7 @@ public void test300SortToWavesXYZCircular() throws Exception { private LensProjectionContext fillContextWithDummyElaineAccount( LensContext context, String dummyName, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, IOException, ExpressionEvaluationException { String resourceOid = getDummyOid(dummyName); - String accountOid = getDummuAccountOid(dummyName,"e"); + String accountOid = getDummuAccountOid(dummyName, "e"); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_ELAINE_TEMPLATE_FILE); ShadowType accountType = account.asObjectable(); accountType.setOid(accountOid); @@ -436,12 +393,12 @@ private LensProjectionContext fillContextWithDummyElaineAccount( private void assertWave(LensContext context, String resourceOid, int order, int expectedWave) { LensProjectionContext ctxAccDummy = findAccountContext(context, resourceOid, order); - assertNotNull("No context for "+resourceOid+", order="+order, ctxAccDummy); + assertNotNull("No context for " + resourceOid + ", order=" + order, ctxAccDummy); assertWave(ctxAccDummy, expectedWave); } private void assertWave(LensProjectionContext projCtx, int expectedWave) { - assertEquals("Wrong wave in "+projCtx, expectedWave, projCtx.getWave()); + assertEquals("Wrong wave in " + projCtx, expectedWave, projCtx.getWave()); } private LensProjectionContext findAccountContext(LensContext context, String resourceOid, int order) { @@ -449,5 +406,4 @@ private LensProjectionContext findAccountContext(LensContext context, discr.setOrder(order); return context.findProjectionContext(discr); } - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules2.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules2.java index eeb397ef622..7f7a05da74c 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules2.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestPolicyRules2.java @@ -6,6 +6,18 @@ */ package com.evolveum.midpoint.model.impl.lens; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.util.HashMap; +import java.util.Map; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRule; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; @@ -27,26 +39,14 @@ import com.evolveum.midpoint.util.exception.PolicyViolationException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.io.File; -import java.util.HashMap; -import java.util.Map; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; /** * Tests some of the "new" policy rules (state, hasAssignment). * Moved out of TestPolicyRules to keep the tests of reasonable size. * * @author mederly - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPolicyRules2 extends AbstractLensTest { @@ -105,11 +105,11 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti .type(RoleType.COMPLEX_TYPE) .filter(prismContext.getQueryConverter().createSearchFilterType(studentFilter))) .beginPolicyConstraints() - .beginHasAssignment() - .name("student-assignment-disabled") - .targetRef(roleStudentOid, RoleType.COMPLEX_TYPE) - .enabled(false) - .end() + .beginHasAssignment() + .name("student-assignment-disabled") + .targetRef(roleStudentOid, RoleType.COMPLEX_TYPE) + .enabled(false) + .end() .end() .evaluationTarget(PolicyRuleEvaluationTargetType.ASSIGNMENT) .policyActions(new PolicyActionsType(prismContext)); @@ -128,10 +128,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100JackAttemptAssignRoleStudent() throws Exception { - final String TEST_NAME = "test100JackAttemptAssignRoleStudent"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -170,10 +168,8 @@ public void test100JackAttemptAssignRoleStudent() throws Exception { */ @Test public void test110JoeAttemptAssignRoleStudent() throws Exception { - final String TEST_NAME = "test110JoeAttemptAssignRoleStudent"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -215,10 +211,8 @@ public void test110JoeAttemptAssignRoleStudent() throws Exception { */ @Test public void test120JackAttemptToMoveTo1900AndAssignRoleStudent() throws Exception { - final String TEST_NAME = "test120JackAttemptToMoveTo1900AndAssignRoleStudent"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -266,10 +260,8 @@ public void test120JackAttemptToMoveTo1900AndAssignRoleStudent() throws Exceptio */ @Test public void test130JackMoveTo1900AndAssignRoleStudent() throws Exception { - final String TEST_NAME = "test130JackMoveTo1900AndAssignRoleStudent"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -320,10 +312,8 @@ public void test130JackMoveTo1900AndAssignRoleStudent() throws Exception { @Test public void test135JackChangeValidTo() throws Exception { - final String TEST_NAME = "test135JackChangeValidTo"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); Long assignmentId = getUser(USER_JACK_OID).asObjectable().getAssignment().get(0).getId(); @@ -364,13 +354,10 @@ public void test135JackChangeValidTo() throws Exception { assertFocusTriggers(context, PolicyConstraintKindType.TRANSITION, 3); } - @Test public void test140JackNoChange() throws Exception { - final String TEST_NAME = "test140JackNoChange"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -407,10 +394,8 @@ public void test140JackNoChange() throws Exception { @Test public void test142JackNoChangeButTaskExists() throws Exception { - final String TEST_NAME = "test142JackNoChangeButTaskExists"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); TaskType approvalTask = prismContext.createObjectable(TaskType.class) @@ -463,13 +448,10 @@ public void test142JackNoChangeButTaskExists() throws Exception { assertFocusTriggers(context, PolicyConstraintKindType.TRANSITION, 3); } - @Test public void test150FrankAttemptToAssignRoleStudentButDisabled() throws Exception { - final String TEST_NAME = "test150FrankAttemptToAssignRoleStudentButDisabled"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -513,10 +495,8 @@ public void test150FrankAttemptToAssignRoleStudentButDisabled() throws Exception @Test public void test160AttemptToAddPeter() throws Exception { - final String TEST_NAME = "test160AttemptToAddPeter"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -552,10 +532,8 @@ public void test160AttemptToAddPeter() throws Exception { @Test public void test170AddPeter() throws Exception { - final String TEST_NAME = "test170AddPeter"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createUserLensContext(); @@ -605,10 +583,8 @@ public void test170AddPeter() throws Exception { */ @Test public void test180StudentRecompute() throws Exception { - final String TEST_NAME = "test180StudentRecompute"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createLensContext(RoleType.class); @@ -640,10 +616,8 @@ public void test180StudentRecompute() throws Exception { @Test public void test200AddUnresolvable() throws Exception { - final String TEST_NAME = "test200AddUnresolvable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createLensContext(RoleType.class); @@ -670,10 +644,8 @@ public void test200AddUnresolvable() throws Exception { @Test public void test210AddCyclic() throws Exception { - final String TEST_NAME = "test210AddCyclic"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createLensContext(RoleType.class); @@ -700,10 +672,8 @@ public void test210AddCyclic() throws Exception { @Test public void test220AddChained() throws Exception { - final String TEST_NAME = "test220AddChained"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createLensContext(RoleType.class); @@ -719,7 +689,7 @@ public void test220AddChained() throws Exception { then(); display("Output context", context); - Map rules = new HashMap<>(); + Map rules = new HashMap<>(); forEvaluatedFocusPolicyRule(context, (r) -> { display("rule", r); rules.put(r.getName(), r); @@ -759,10 +729,8 @@ public void test220AddChained() throws Exception { @Test public void test230AddAmbiguous() throws Exception { - final String TEST_NAME = "test230AddAmbiguous"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); LensContext context = createLensContext(RoleType.class); @@ -790,10 +758,8 @@ public void test230AddAmbiguous() throws Exception { // MID-4270 @Test public void test300ModifyInducement() throws Exception { - final String TEST_NAME = "test300ModifyInducement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta delta = prismContext.deltaFor(RoleType.class) @@ -824,10 +790,8 @@ public void test300ModifyInducement() throws Exception { // MID-4270 @Test public void test310ModifyInducementPass() throws Exception { - final String TEST_NAME = "test310ModifyInducementPass"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta delta = prismContext.deltaFor(RoleType.class) @@ -850,10 +814,8 @@ public void test310ModifyInducementPass() throws Exception { // MID-4270 @Test public void test320ModifyInducementPass2() throws Exception { - final String TEST_NAME = "test320ModifyInducementPass2"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta delta = prismContext.deltaFor(RoleType.class) @@ -876,10 +838,8 @@ public void test320ModifyInducementPass2() throws Exception { // MID-4270 @Test public void test330AddInducement() throws Exception { - final String TEST_NAME = "test330AddInducement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta delta = prismContext.deltaFor(RoleType.class) @@ -910,10 +870,8 @@ public void test330AddInducement() throws Exception { // MID-4270 @Test public void test340AddInducementViaExpression() throws Exception { - final String TEST_NAME = "test340AddInducementViaExpression"; - // GIVEN - Task task = taskManager.createTaskInstance(TestPolicyRules2.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta delta = prismContext.deltaFor(RoleType.class) diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjector.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjector.java index 9e6cbe449a1..881cfa47d4f 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjector.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjector.java @@ -6,17 +6,16 @@ */ package com.evolveum.midpoint.model.impl.lens; -import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; import static org.testng.AssertJUnit.*; +import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; + import java.io.File; import java.util.Collection; import java.util.Iterator; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.delta.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -29,6 +28,7 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.PrismReference; +import com.evolveum.midpoint.prism.delta.*; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; @@ -43,30 +43,13 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TriggerType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestProjector extends AbstractLensTest { @@ -83,20 +66,15 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // repoAddObjectFromFile(SECURITY_POLICY_FILE, initResult); InternalMonitor.reset(); -// InternalMonitor.setTraceShadowFetchOperation(true); } @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - assertNoJackShadow(); } @Test public void test010BasicContextOperations() throws Exception { - final String TEST_NAME = "test010BasicContextOperations"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -177,11 +155,8 @@ public void test010BasicContextOperations() throws Exception { } - @Test public void test100AddAccountToJackDirect() throws Exception { - final String TEST_NAME = "test100AddAccountToJackDirect"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -208,7 +183,7 @@ public void test100AddAccountToJackDirect() throws Exception { // Not loading anything. The account is already loaded in the context assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - assertNull("Unexpected user primary changes "+context.getFocusContext().getPrimaryDelta(), context.getFocusContext().getPrimaryDelta()); + assertNull("Unexpected user primary changes " + context.getFocusContext().getPrimaryDelta(), context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "user secondary delta", ActivationStatusType.ENABLED); assertFalse("No account changes", context.getProjectionContexts().isEmpty()); @@ -247,8 +222,6 @@ public void test100AddAccountToJackDirect() throws Exception { @Test public void test110AssignAccountToJack() throws Exception { - final String TEST_NAME = "test110AssignAccountToJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -275,8 +248,6 @@ public void test110AssignAccountToJack() throws Exception { */ @Test public void test111AssignAccountToJackBroken() throws Exception { - final String TEST_NAME = "test111AssignAccountToJackBroken"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -317,29 +288,26 @@ private void assertAssignAccountToJack(LensContext context) { ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertEquals("Wrong decision", SynchronizationPolicyDecision.ADD,accContext.getSynchronizationPolicyDecision()); + assertEquals("Wrong decision", SynchronizationPolicyDecision.ADD, accContext.getSynchronizationPolicyDecision()); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getIcfsNameAttributePath() , "jack"); + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getIcfsNameAttributePath(), "jack"); PrismAsserts.assertPropertyReplace(accountSecondaryDelta, - getDummyResourceController().getAttributeFullnamePath() , "Jack Sparrow"); + getDummyResourceController().getAttributeFullnamePath(), "Jack Sparrow"); PrismAsserts.assertPropertyAdd(accountSecondaryDelta, - getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME) , "mouth", "pistol"); + getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEAPON_NAME), "mouth", "pistol"); PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.OUTBOUND); } - /** * User barbossa has a direct account assignment. This assignment has an expression for user/locality -> dummy/location. * Let's try if the "l" gets updated if we update barbosa's locality. */ @Test public void test250ModifyUserBarbossaLocality() throws Exception { - final String TEST_NAME = "test250ModifyUserBarbossaLocality"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -369,13 +337,13 @@ public void test250ModifyUserBarbossaLocality() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); assertEquals("Unexpected number of account secondary changes", 3, accountSecondaryDelta.getModifications().size()); PrismAsserts.assertPropertyReplace(accountSecondaryDelta, - getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME) , "Tortuga"); + getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_LOCATION_NAME), "Tortuga"); PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.ASSIGNMENTS, OriginType.OUTBOUND); @@ -388,8 +356,6 @@ public void test250ModifyUserBarbossaLocality() throws Exception { */ @Test public void test251ModifyUserBarbossaFullname() throws Exception { - final String TEST_NAME = "test251ModifyUserBarbossaFullname"; - // GIVEN Task task = getTestTask(); @@ -420,13 +386,13 @@ public void test251ModifyUserBarbossaFullname() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); assertEquals("Unexpected number of account secondary changes", 3, accountSecondaryDelta.getModifications().size()); PrismAsserts.assertPropertyReplace(accountSecondaryDelta, - getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME) , + getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Captain Hector Barbossa"); PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.OUTBOUND); @@ -439,8 +405,6 @@ public void test251ModifyUserBarbossaFullname() throws Exception { */ @Test public void test254ModifyUserBarbossaDisable() throws Exception { - final String TEST_NAME = "test254ModifyUserBarbossaDisable"; - // GIVEN Task task = getTestTask(); @@ -471,7 +435,7 @@ public void test254ModifyUserBarbossaDisable() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta", accountSecondaryDelta); @@ -501,8 +465,6 @@ public void test254ModifyUserBarbossaDisable() throws Exception { */ @Test public void test255ModifyUserBarbossaAssignment() throws Exception { - final String TEST_NAME = "test255ModifyUserBarbossaAssignment"; - // GIVEN Task task = getTestTask(); @@ -534,7 +496,7 @@ public void test255ModifyUserBarbossaAssignment() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta", accountSecondaryDelta); @@ -554,8 +516,6 @@ public void test255ModifyUserBarbossaAssignment() throws Exception { */ @Test public void test260ModifyAccountBarbossaDrinkReplace() throws Exception { - final String TEST_NAME = "test260ModifyAccountBarbossaDrinkReplace"; - // GIVEN Task task = getTestTask(); @@ -590,8 +550,6 @@ public void test260ModifyAccountBarbossaDrinkReplace() throws Exception { */ @Test public void test261ModifyAccountBarbossaQuoteReplace() throws Exception { - final String TEST_NAME = "test261ModifyAccountBarbossaQuoteReplace"; - // GIVEN Task task = getTestTask(); @@ -627,32 +585,29 @@ public void test261ModifyAccountBarbossaQuoteReplace() throws Exception { assertEquals(ChangeType.MODIFY, accountPrimaryDelta.getChangeType()); assertEquals("Unexpected number of account secondary changes", 1, accountPrimaryDelta.getModifications().size()); PrismAsserts.assertPropertyReplace(accountPrimaryDelta, - getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME) , + getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), "I'm disinclined to acquiesce to your request."); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta", accountSecondaryDelta); assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); assertEquals("Unexpected number of account secondary changes", 3, accountSecondaryDelta.getModifications().size()); PrismAsserts.assertPropertyAdd(accountSecondaryDelta, - getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME) , + getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME), "Arr!"); PrismAsserts.assertOrigin(accountSecondaryDelta, OriginType.OUTBOUND); } - /** * User barbossa has a direct account assignment. * Let's try to delete assigned account. It should end up with a policy violation error. */ @Test public void test269DeleteBarbossaDummyAccount() throws Exception { - final String TEST_NAME = "test269DeleteBarbossaDummyAccount"; - // GIVEN Task task = getTestTask(); @@ -680,15 +635,13 @@ public void test269DeleteBarbossaDummyAccount() throws Exception { } catch (PolicyViolationException e) { // THEN: success // this is expected - display("Expected exception",e); + display("Expected exception", e); } } @Test public void test270AddUserBarbossaAssignmentBrethren() throws Exception { - final String TEST_NAME = "test270AddUserBarbossaAssignmentBrethren"; - // GIVEN Task task = getTestTask(); @@ -721,7 +674,7 @@ public void test270AddUserBarbossaAssignmentBrethren() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta", accountSecondaryDelta); @@ -733,8 +686,6 @@ public void test270AddUserBarbossaAssignmentBrethren() throws Exception { @Test public void test275DeleteUserBarbossaAssignmentBrethren() throws Exception { - final String TEST_NAME = "test275DeleteUserBarbossaAssignmentBrethren"; - // GIVEN Task task = getTestTask(); @@ -775,14 +726,11 @@ public void test275DeleteUserBarbossaAssignmentBrethren() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); - + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); } @Test public void test280AddUserBarbossaAssignmentMutinier() throws Exception { - final String TEST_NAME = "test280AddUserBarbossaAssignmentMutinier"; - // GIVEN Task task = getTestTask(); @@ -814,7 +762,7 @@ public void test280AddUserBarbossaAssignmentMutinier() throws Exception { assertEquals(1, accountContexts.size()); LensProjectionContext accContext = accountContexts.iterator().next(); assertNull(accContext.getPrimaryDelta()); - assertEquals(SynchronizationPolicyDecision.KEEP,accContext.getSynchronizationPolicyDecision()); + assertEquals(SynchronizationPolicyDecision.KEEP, accContext.getSynchronizationPolicyDecision()); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); assertNotNull("No account secondary delta", accountSecondaryDelta); @@ -828,8 +776,6 @@ public void test280AddUserBarbossaAssignmentMutinier() throws Exception { @Test public void test301AssignConflictingAccountToJack() throws Exception { - final String TEST_NAME = "test301AssignConflictingAccountToJack"; - // GIVEN Task task = getTestTask(); @@ -871,13 +817,11 @@ public void test301AssignConflictingAccountToJack() throws Exception { assertEquals(ChangeType.MODIFY, accountSecondaryDelta.getChangeType()); - PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getDummyResourceController().getAttributeFullnamePath() , "Jack Sparrow"); + PrismAsserts.assertPropertyReplace(accountSecondaryDelta, getDummyResourceController().getAttributeFullnamePath(), "Jack Sparrow"); } @Test public void test400ImportHermanDummy() throws Exception { - final String TEST_NAME = "test400ImportHermanDummy"; - // GIVEN Task task = getTestTask(); @@ -886,7 +830,7 @@ public void test400ImportHermanDummy() throws Exception { LensContext context = createUserLensContext(); context.setChannel(SchemaConstants.CHANGE_CHANNEL_IMPORT); - fillContextWithEmtptyAddUserDelta(context, result); + fillContextWithEmtptyAddUserDelta(context); fillContextWithAccountFromFile(context, ACCOUNT_HERMAN_DUMMY_FILE, task, result); makeImportSyncDelta(context.getProjectionContexts().iterator().next()); context.recompute(); @@ -933,8 +877,6 @@ public void test400ImportHermanDummy() throws Exception { @Test public void test401ImportHermanDummy() throws Exception { - final String TEST_NAME = "test401ImportHermanDummy"; - // GIVEN Task task = getTestTask(); @@ -943,7 +885,7 @@ public void test401ImportHermanDummy() throws Exception { LensContext context = createUserLensContext(); context.setChannel(SchemaConstants.CHANGE_CHANNEL_IMPORT); - fillContextWithEmtptyAddUserDelta(context, result); + fillContextWithEmtptyAddUserDelta(context); fillContextWithAccountFromFile(context, ACCOUNT_HERMAN_DUMMY_FILE, task, result); makeImportSyncDelta(context.getProjectionContexts().iterator().next()); context.recompute(); @@ -979,8 +921,6 @@ public void test401ImportHermanDummy() throws Exception { @Test public void test450GuybrushInboundFromDelta() throws Exception { - final String TEST_NAME = "test450GuybrushInboundFromDelta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1006,15 +946,13 @@ public void test450GuybrushInboundFromDelta() throws Exception { assertUserSecondaryDelta(context); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); assertTrue(userSecondaryDelta.getChangeType() == ChangeType.MODIFY); - PrismAsserts.assertPropertyAdd(userSecondaryDelta, UserType.F_ORGANIZATIONAL_UNIT , + PrismAsserts.assertPropertyAdd(userSecondaryDelta, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of Black Pearl")); assertOriginWithSideEffectChanges(userSecondaryDelta, OriginType.INBOUND); } @Test public void test451GuybrushInboundFromAbsolute() throws Exception { - final String TEST_NAME = "test451GuybrushInboundFromAbsolute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1046,16 +984,13 @@ public void test451GuybrushInboundFromAbsolute() throws Exception { assertUserSecondaryDelta(context); ObjectDelta userSecondaryDelta = context.getFocusContext().getSecondaryDelta(); assertTrue(userSecondaryDelta.getChangeType() == ChangeType.MODIFY); - PrismAsserts.assertPropertyAdd(userSecondaryDelta, UserType.F_ORGANIZATIONAL_UNIT , + PrismAsserts.assertPropertyAdd(userSecondaryDelta, UserType.F_ORGANIZATIONAL_UNIT, PrismTestUtil.createPolyString("The crew of The Sea Monkey")); assertOriginWithSideEffectChanges(userSecondaryDelta, OriginType.INBOUND); } - @Test public void test500ReconcileGuybrushDummy() throws Exception { - final String TEST_NAME = "test500ReconcileGuybrushDummy"; - // GIVEN Task task = getTestTask(); @@ -1110,7 +1045,6 @@ public void test500ReconcileGuybrushDummy() throws Exception { assertNotNull("No location delta in projection secondary delta", locationDelta); PrismAsserts.assertReplace(locationDelta, "Melee Island"); PrismAsserts.assertOrigin(locationDelta, OriginType.RECONCILIATION); - } /** @@ -1118,8 +1052,6 @@ public void test500ReconcileGuybrushDummy() throws Exception { */ @Test public void test600AddLargo() throws Exception { - final String TEST_NAME = "test600AddLargo"; - // GIVEN Task task = getTestTask(); @@ -1177,8 +1109,6 @@ private void assertOriginWithSideEffectChanges(ObjectDelta delta, Orig iterator.remove(); } } - PrismAsserts.assertOrigin(delta,expectedOrigi); + PrismAsserts.assertOrigin(delta, expectedOrigi); } - - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorPersona.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorPersona.java index 10cc9f65ced..90b617ffb99 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorPersona.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorPersona.java @@ -6,10 +6,7 @@ */ package com.evolveum.midpoint.model.impl.lens; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -25,17 +22,9 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PersonaConstructionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestProjectorPersona extends AbstractLensTest { @@ -45,15 +34,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti setDefaultUserTemplate(USER_TEMPLATE_OID); addObject(ROLE_PERSONA_ADMIN_FILE); InternalMonitor.reset(); -// InternalMonitor.setTraceShadowFetchOperation(true); } @Test public void test100AssignRolePersonaAdminToJack() throws Exception { - final String TEST_NAME = "test100AssignRolePersonaAdminToJack"; - // GIVEN - Task task = taskManager.createTaskInstance(TestProjectorPersona.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -101,11 +87,7 @@ public void test100AssignRolePersonaAdminToJack() throws Exception { assertNotNull("No personaConstruction", personaConstruction); PersonaConstructionType personaConstructionType = personaConstruction.getConstructionType(); assertNotNull("No personaConstructionType", personaConstructionType); - assertTrue("Wrong type: "+personaConstructionType.getTargetType(), QNameUtil.match(UserType.COMPLEX_TYPE, personaConstructionType.getTargetType())); + assertTrue("Wrong type: " + personaConstructionType.getTargetType(), QNameUtil.match(UserType.COMPLEX_TYPE, personaConstructionType.getTargetType())); PrismAsserts.assertEqualsCollectionUnordered("Wrong subtype", personaConstructionType.getTargetSubtype(), "admin"); - } - - - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorRoleEntitlement.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorRoleEntitlement.java index d4001d796ec..48775302987 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorRoleEntitlement.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestProjectorRoleEntitlement.java @@ -8,7 +8,6 @@ import static org.testng.AssertJUnit.*; -import java.io.File; import java.util.Collection; import javax.xml.namespace.QName; @@ -31,7 +30,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @@ -39,19 +37,13 @@ /** * @author semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestProjectorRoleEntitlement extends AbstractLensTest { - public static final File USER_BARBOSSA_MODIFY_ASSIGNMENT_REPLACE_AC_FILE = new File(TEST_DIR, - "user-barbossa-modify-assignment-replace-ac.xml"); - - @Autowired(required = true) + @Autowired private Projector projector; - @Autowired(required = true) - private TaskManager taskManager; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -69,10 +61,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100AddEntitlementToPirateDirect() throws Exception { - final String TEST_NAME = "test100AddEntitlementToPirateDirect"; - // GIVEN - Task task = taskManager.createTaskInstance(TestProjectorRoleEntitlement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); @@ -91,7 +81,7 @@ public void test100AddEntitlementToPirateDirect() throws Exception { // THEN display("Output context", context); - assertNull("Unexpected focus primary changes "+context.getFocusContext().getPrimaryDelta(), context.getFocusContext().getPrimaryDelta()); + assertNull("Unexpected focus primary changes " + context.getFocusContext().getPrimaryDelta(), context.getFocusContext().getPrimaryDelta()); assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "focus secondary delta", ActivationStatusType.ENABLED); assertFalse("No projection contexts", context.getProjectionContexts().isEmpty()); @@ -131,10 +121,8 @@ public void test100AddEntitlementToPirateDirect() throws Exception { @Test public void test110AssignEntitlementToPirate() throws Exception { - final String TEST_NAME = "test110AssignEntitlementToPirate"; - // GIVEN - Task task = taskManager.createTaskInstance(TestProjectorRoleEntitlement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -160,10 +148,8 @@ public void test110AssignEntitlementToPirate() throws Exception { */ @Test public void test111AssignEntitlementToPirateBroken() throws Exception { - final String TEST_NAME = "test110AssignEntitlementToPirate"; - // GIVEN - Task task = taskManager.createTaskInstance(TestProjectorRoleEntitlement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -190,8 +176,9 @@ public void test111AssignEntitlementToPirateBroken() throws Exception { private void assertAssignEntitlementToPirate(LensContext context) { display("Output context", context); - assertTrue(context.getFocusContext().getPrimaryDelta().getChangeType() == ChangeType.MODIFY); - assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), "focus secondary delta", ActivationStatusType.ENABLED); + assertSame(context.getFocusContext().getPrimaryDelta().getChangeType(), ChangeType.MODIFY); + assertSideEffectiveDeltasOnly(context.getFocusContext().getSecondaryDelta(), + "focus secondary delta", ActivationStatusType.ENABLED); assertFalse("No projection changes", context.getProjectionContexts().isEmpty()); Collection projectionContexts = context.getProjectionContexts(); @@ -201,11 +188,11 @@ private void assertAssignEntitlementToPirate(LensContext context) { ObjectDelta projSecondaryDelta = projContext.getSecondaryDelta(); - assertEquals("Wrong decision", SynchronizationPolicyDecision.ADD,projContext.getSynchronizationPolicyDecision()); + assertEquals("Wrong decision", SynchronizationPolicyDecision.ADD, projContext.getSynchronizationPolicyDecision()); assertEquals(ChangeType.MODIFY, projSecondaryDelta.getChangeType()); - PrismAsserts.assertPropertyReplace(projSecondaryDelta, getIcfsNameAttributePath() , "Pirate"); + PrismAsserts.assertPropertyReplace(projSecondaryDelta, getIcfsNameAttributePath(), "Pirate"); PrismAsserts.assertPropertyReplace(projSecondaryDelta, getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION), "Bloody pirates"); @@ -213,5 +200,4 @@ private void assertAssignEntitlementToPirate(LensContext context) { } - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java index 57cf7c7c597..78e2e892d98 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java @@ -6,6 +6,8 @@ */ package com.evolveum.midpoint.model.impl.lens; +import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_MODEL_EXTENSION_DRY_RUN; + import java.io.File; import java.util.ArrayList; import java.util.Collection; @@ -28,15 +30,9 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.asserter.ShadowAsserter; import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_MODEL_EXTENSION_DRY_RUN; - -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestReconScript extends AbstractInternalModelIntegrationTest { @@ -47,10 +43,8 @@ public class TestReconScript extends AbstractInternalModelIntegrationTest { private static final String ACCOUNT_BEFORE_SCRIPT_OID = "acc00000-0000-0000-0000-000000001234"; @Test - public void text001testReconcileScriptsWhenProvisioning() throws Exception{ - final String TEST_NAME = "text001testReconcileScriptsWhenProvisioning"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + public void text001testReconcileScriptsWhenProvisioning() throws Exception { + Task task = getTestTask(); OperationResult parentResult = createOperationResult(); ObjectDelta delta = createModifyUserAddAccount(USER_JACK_OID, getDummyResourceObject()); @@ -72,26 +66,23 @@ public void text001testReconcileScriptsWhenProvisioning() throws Exception{ modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, parentResult); - - for (ScriptHistoryEntry script : getDummyResource().getScriptHistory()){ + for (ScriptHistoryEntry script : getDummyResource().getScriptHistory()) { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", new Object[]{userName,idPath,tempPath}); - if (!idPath.contains(userName)){ - AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName +"]"); + LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + if (!idPath.contains(userName)) { + AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } - if (!tempPath.contains(userName)){ - AssertJUnit.fail("Expected that tempPath will contain userName [idPath: " + idPath + ", userName " + userName +"]"); + if (!tempPath.contains(userName)) { + AssertJUnit.fail("Expected that tempPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } } } @Test - public void test002testReconcileScriptsWhenReconciling() throws Exception{ - final String TEST_NAME = "test002testReconcileScriptsWhenReconciling"; - + public void test002testReconcileScriptsWhenReconciling() throws Exception { getDummyResource().getScriptHistory().clear(); importObjectFromFile(new File(TASK_RECON_DUMMY_FILENAME)); @@ -102,25 +93,23 @@ public void test002testReconcileScriptsWhenReconciling() throws Exception{ waitForTaskFinish(TASK_RECON_DUMMY_OID, false); - for (ScriptHistoryEntry script : getDummyResource().getScriptHistory()){ - + for (ScriptHistoryEntry script : getDummyResource().getScriptHistory()) { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", new Object[]{userName,idPath,tempPath}); - if (!idPath.contains(userName)){ - AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName +"]"); + LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + if (!idPath.contains(userName)) { + AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } - if (!tempPath.contains(userName)){ - AssertJUnit.fail("Expected that tempPath will contain userName [idPath: " + idPath + ", userName " + userName +"]"); + if (!tempPath.contains(userName)) { + AssertJUnit.fail("Expected that tempPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } } - } @Test - public void test003testReconcileScriptsAddUserAction() throws Exception{ + public void test003testReconcileScriptsAddUserAction() throws Exception { final String TEST_NAME = "test003testReconcileScriptsAddUserAction"; Task task = taskManager.createTaskInstance(TEST_NAME); @@ -141,45 +130,42 @@ public void test003testReconcileScriptsAddUserAction() throws Exception{ PrismObject afterRecon = repositoryService.getObject(ShadowType.class, ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); AssertJUnit.assertNotNull(afterRecon); - ShadowType afterReconShadow = afterRecon.asObjectable(); + afterRecon.asObjectable(); PrismObject user = repositoryService.searchShadowOwner(ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); AssertJUnit.assertNotNull("Owner for account " + shadow.asPrismObject() + " not found. Some probelm in recon occured.", user); - - for (ScriptHistoryEntry script : getDummyResource().getScriptHistory()){ + for (ScriptHistoryEntry script : getDummyResource().getScriptHistory()) { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", new Object[]{userName,idPath,tempPath}); - if (!idPath.contains(userName)){ - AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName +"]"); + LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + if (!idPath.contains(userName)) { + AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } - if (!tempPath.contains(userName)){ - AssertJUnit.fail("Expected that tempPath will contain userName [idPath: " + idPath + ", userName " + userName +"]"); + if (!tempPath.contains(userName)) { + AssertJUnit.fail("Expected that tempPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } } - } @Test - public void test005TestDryRunDelete() throws Exception{ - final String TEST_NAME = "test005TestDryRunDelete"; - + public void test005TestDryRunDelete() throws Exception { PrismObject task = getTask(TASK_RECON_DUMMY_OID); OperationResult parentResult = createOperationResult(); - PropertyDelta dryRunDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(PATH_MODEL_EXTENSION_DRY_RUN, task.getDefinition(), true); - Collection modifications = new ArrayList<>(); + PropertyDelta dryRunDelta = + prismContext.deltaFactory().property().createModificationReplaceProperty( + PATH_MODEL_EXTENSION_DRY_RUN, task.getDefinition(), true); + Collection> modifications = new ArrayList<>(); modifications.add(dryRunDelta); repositoryService.modifyObject(TaskType.class, TASK_RECON_DUMMY_OID, modifications, parentResult); getDummyResource().deleteAccountByName("beforeScript"); - waitForTaskStart(TASK_RECON_DUMMY_OID, false); waitForTaskNextRunAssertSuccess(TASK_RECON_DUMMY_OID, false); @@ -191,20 +177,16 @@ public void test005TestDryRunDelete() throws Exception{ PrismObject user = repositoryService.searchShadowOwner(ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); AssertJUnit.assertNotNull("Owner for account " + shadow + " not found. Some probelm in dry run occured.", user); - - } @Test - public void test006TestReconDelete() throws Exception{ - final String TEST_NAME = "test006TestReconDelete"; - + public void test006TestReconDelete() throws Exception { PrismObject task = getTask(TASK_RECON_DUMMY_OID); OperationResult parentResult = createOperationResult(); PropertyDelta dryRunDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( PATH_MODEL_EXTENSION_DRY_RUN, task.getDefinition(), false); - Collection modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(dryRunDelta); repositoryService.modifyObject(TaskType.class, TASK_RECON_DUMMY_OID, modifications, parentResult); @@ -223,13 +205,11 @@ public void test006TestReconDelete() throws Exception{ PrismObject shadow = repositoryService.getObject(ShadowType.class, ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); ShadowAsserter.forShadow(shadow) - .assertDead() - .assertIsNotExists(); + .assertDead() + .assertIsNotExists(); PrismObject user = repositoryService.searchShadowOwner(ACCOUNT_BEFORE_SCRIPT_OID, null, parentResult); display("Account owner", user); AssertJUnit.assertNotNull("Owner for account " + ACCOUNT_BEFORE_SCRIPT_OID + " was not found", user); - - } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/ShadowIntegrityCheckerTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/ShadowIntegrityCheckerTest.java index 1946f65eb3d..71b78fba2e0 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/ShadowIntegrityCheckerTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/ShadowIntegrityCheckerTest.java @@ -6,6 +6,17 @@ */ package com.evolveum.midpoint.model.impl.misc; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.util.List; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.SearchResultList; @@ -14,22 +25,8 @@ import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; -import java.io.File; -import java.util.List; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; - -/** - * @author mederly - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class ShadowIntegrityCheckerTest extends AbstractInternalModelIntegrationTest { @@ -64,8 +61,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100FixDuplicatesWithDifferentObjectClasses() throws Exception { - final String TEST_NAME = "test100FixDuplicatesWithDifferentObjectClasses"; - login(userAdministrator); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -97,6 +92,4 @@ public void test100FixDuplicatesWithDifferentObjectClasses() throws Exception { .filter(o -> "intent1".equals(o.asObjectable().getIntent())).findFirst().orElse(null); assertNotNull("intent1 shadow was removed", intent1); } - - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestCaseManagement.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestCaseManagement.java index 2ffe0f3ecda..8641a4be1ee 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestCaseManagement.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestCaseManagement.java @@ -18,7 +18,6 @@ import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CaseWorkItemType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -29,10 +28,6 @@ import static org.testng.AssertJUnit.assertEquals; -/** - * @author mederly - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestCaseManagement extends AbstractInternalModelIntegrationTest { @@ -49,24 +44,19 @@ public class TestCaseManagement extends AbstractInternalModelIntegrationTest { @Autowired protected Clockwork clockwork; @Autowired protected TaskManager taskManager; - private PrismObject user1, user2; - private PrismObject case1, case2, case3; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - user1 = repoAddObjectFromFile(USER1_FILE, initResult); - user2 = repoAddObjectFromFile(USER2_FILE, initResult); - case1 = repoAddObjectFromFile(CASE1_FILE, initResult); - case2 = repoAddObjectFromFile(CASE2_FILE, initResult); - case3 = repoAddObjectFromFile(CASE3_FILE, initResult); + repoAddObjectFromFile(USER1_FILE, initResult); + repoAddObjectFromFile(USER2_FILE, initResult); + repoAddObjectFromFile(CASE1_FILE, initResult); + repoAddObjectFromFile(CASE2_FILE, initResult); + repoAddObjectFromFile(CASE3_FILE, initResult); } @Test public void test100SearchCases() throws Exception { - final String TEST_NAME = "test100CreateCase"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); login(userAdministrator); @@ -75,7 +65,5 @@ public void test100SearchCases() throws Exception { assertEquals(3, cases.size()); SearchResultList workItems = controller.searchContainers(CaseWorkItemType.class, null, null, task, result); assertEquals(4, workItems.size()); - } - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestRelationRegistry.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestRelationRegistry.java index ff07b129b94..2e648965d11 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestRelationRegistry.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/misc/TestRelationRegistry.java @@ -32,10 +32,6 @@ import static org.springframework.test.util.AssertionErrors.assertNotEquals; import static org.testng.AssertJUnit.*; -/** - * @author mederly - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRelationRegistry extends AbstractInternalModelIntegrationTest { @@ -53,8 +49,6 @@ public class TestRelationRegistry extends AbstractInternalModelIntegrationTest { @Test public void test100DefaultRelations() { - final String TEST_NAME = "test100DefaultRelations"; - assertEquals("Wrong # of default relations", RelationTypes.values().length, relationRegistry.getRelationDefinitions().size()); RelationDefinitionType orgDefaultDef = relationRegistry.getRelationDefinition(SchemaConstants.ORG_DEFAULT); @@ -134,8 +128,6 @@ public void test100DefaultRelations() { @Test public void test110AddedCustomRelations() throws SchemaException, IOException { - final String TEST_NAME = "test110AddedCustomRelations"; - PrismObject sysconfigObject = prismContext.parseObject(SYSCONFIG_ADDED_CUSTOM_RELATIONS_FILE); relationRegistry.applyRelationsConfiguration(sysconfigObject.asObjectable()); @@ -255,8 +247,6 @@ public void test110AddedCustomRelations() throws SchemaException, IOException { @Test public void test120ReplacedAllRelations() throws SchemaException, IOException { - final String TEST_NAME = "test120ReplacedAllRelations"; - PrismObject sysconfigObject = prismContext.parseObject(SYSCONFIG_REPLACED_ALL_RELATIONS_FILE); relationRegistry.applyRelationsConfiguration(sysconfigObject.asObjectable()); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestAbstractAuthenticationEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestAbstractAuthenticationEvaluator.java index 75719d77874..98dcb11e75a 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestAbstractAuthenticationEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestAbstractAuthenticationEvaluator.java @@ -628,7 +628,6 @@ public void test137PasswordLoginLockedoutGoodPasswordAgain() throws Exception { @Test public void test138UnlockUserGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -671,7 +670,6 @@ public void test138UnlockUserGoodPassword() throws Exception { @Test public void test139TryToLockByModelService() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -700,7 +698,6 @@ public void test139TryToLockByModelService() throws Exception { @Test public void test150PasswordLoginDisabledGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); @@ -711,7 +708,6 @@ public void test150PasswordLoginDisabledGoodPassword() throws Exception { @Test public void test152PasswordLoginEnabledGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); @@ -722,7 +718,6 @@ public void test152PasswordLoginEnabledGoodPassword() throws Exception { @Test public void test154PasswordLoginNotValidYetGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -741,8 +736,6 @@ public void test155PasswordLoginValidGoodPassword() throws Exception { // GIVEN clock.overrideDuration("PT2H"); - TestAbstractAuthenticationEvaluator.class.getName(); - loginJackGoodPasswordExpectSuccess(); } @@ -751,15 +744,12 @@ public void test156PasswordLoginNotValidAnyLongerGoodPassword() throws Exception // GIVEN clock.overrideDuration("P2D"); - TestAbstractAuthenticationEvaluator.class.getName(); - loginJackGoodPasswordExpectDenied(); } @Test public void test159PasswordLoginNoLongerValidEnabledGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); @@ -770,7 +760,6 @@ public void test159PasswordLoginNoLongerValidEnabledGoodPassword() throws Except @Test public void test160PasswordLoginLifecycleActiveGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -783,7 +772,6 @@ public void test160PasswordLoginLifecycleActiveGoodPassword() throws Exception { @Test public void test162PasswordLoginLifecycleDraftGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -796,7 +784,6 @@ public void test162PasswordLoginLifecycleDraftGoodPassword() throws Exception { @Test public void test164PasswordLoginLifecycleDeprecatedGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -809,7 +796,6 @@ public void test164PasswordLoginLifecycleDeprecatedGoodPassword() throws Excepti @Test public void test166PasswordLoginLifecycleProposedGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -822,7 +808,6 @@ public void test166PasswordLoginLifecycleProposedGoodPassword() throws Exception @Test public void test168PasswordLoginLifecycleArchivedGoodPassword() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -835,7 +820,6 @@ public void test168PasswordLoginLifecycleArchivedGoodPassword() throws Exception @Test public void test200UserGuybrushSetCredentials() throws Exception { // GIVEN - TestAbstractAuthenticationEvaluator.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestGuiProfiledPrincipalManager.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestGuiProfiledPrincipalManager.java index a33e76abd0a..ee075d142db 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestGuiProfiledPrincipalManager.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/security/TestGuiProfiledPrincipalManager.java @@ -7,77 +7,73 @@ package com.evolveum.midpoint.model.impl.security; -import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.security.api.DelegatorWithOtherPrivilegesLimitations; -import com.evolveum.midpoint.security.api.MidPointPrincipal; -import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.exception.CommonException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; +import static org.testng.AssertJUnit.assertEquals; + +import static com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType.DISABLED; -import javax.xml.bind.JAXBElement; -import javax.xml.namespace.QName; import java.util.Collection; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.function.Consumer; +import javax.xml.bind.JAXBElement; +import javax.xml.namespace.QName; -import static com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType.DISABLED; -import static org.testng.AssertJUnit.assertEquals; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; -/** - * @author mederly - */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.security.api.DelegatorWithOtherPrivilegesLimitations; +import com.evolveum.midpoint.security.api.MidPointPrincipal; +import com.evolveum.midpoint.util.DebugUtil; +import com.evolveum.midpoint.util.exception.CommonException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestGuiProfiledPrincipalManager extends AbstractInternalModelIntegrationTest { @Test public void test100DeputyNoLimits() throws Exception { - final String TEST_NAME = "test100DeputyNoLimits"; - executeDeputyLimitationsTest(TEST_NAME, Collections.emptyList(), null); + executeDeputyLimitationsTest(Collections.emptyList(), null); } @Test // MID-4111 public void test110DeputyAssignmentDisabled() throws Exception { - final String TEST_NAME = "test110DeputyAssignmentDisabled"; - executeDeputyLimitationsTest(TEST_NAME, null, + executeDeputyLimitationsTest(null, (a) -> a.setActivation(new ActivationType().administrativeStatus(DISABLED))); } @Test // MID-4111 public void test120DeputyAssignmentNotValid() throws Exception { - final String TEST_NAME = "test120DeputyAssignmentNotValid"; - executeDeputyLimitationsTest(TEST_NAME, null, + executeDeputyLimitationsTest(null, (a) -> a.setActivation(new ActivationType().validTo("2017-03-31T00:00:00+01:00"))); } @Test public void test130DeputyAssignmentFalseCondition() throws Exception { - final String TEST_NAME = "test130DeputyAssignmentFalseCondition"; - executeDeputyLimitationsTest(TEST_NAME, null, + executeDeputyLimitationsTest(null, (a) -> a.beginCondition() - .beginExpression() - .expressionEvaluator( - new JAXBElement(new QName("script"), - ScriptExpressionEvaluatorType.class, - new ScriptExpressionEvaluatorType().code("false")) - )); + .beginExpression() + .expressionEvaluator( + new JAXBElement(new QName("script"), + ScriptExpressionEvaluatorType.class, + new ScriptExpressionEvaluatorType().code("false")) + )); } @Test public void test140DeputyBlockOtherPrivileges() throws Exception { - final String TEST_NAME = "test140DeputyBlockOtherPrivileges"; - executeDeputyLimitationsTest(TEST_NAME, Collections.singletonList(new OtherPrivilegesLimitationType()), + executeDeputyLimitationsTest(Collections.singletonList(new OtherPrivilegesLimitationType()), (a) -> a.limitOtherPrivileges(new OtherPrivilegesLimitationType())); } - private void executeDeputyLimitationsTest(String TEST_NAME, List expectedLimitations, - Consumer assignmentModifier) throws CommonException { + private void executeDeputyLimitationsTest( + List expectedLimitations, + Consumer assignmentModifier) + throws CommonException { // GIVEN AssignmentType assignment = new AssignmentType() @@ -99,7 +95,8 @@ private void executeDeputyLimitationsTest(String TEST_NAME, List delegators = principal.getDelegatorWithOtherPrivilegesLimitationsCollection(); + Collection delegators = + principal.getDelegatorWithOtherPrivilegesLimitationsCollection(); display("delegators with other privileges limitations", delegators); if (expectedLimitations == null) { assertEquals("Wrong # of delegator records: " + DebugUtil.debugDump(delegators), 0, delegators.size()); @@ -109,5 +106,4 @@ private void executeDeputyLimitationsTest(String TEST_NAME, List(expectedLimitations), new HashSet<>(record.getLimitations())); } } - } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java index 299a06df3ae..25b0eafa828 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java @@ -16,7 +16,6 @@ import java.util.Collection; import java.util.List; -import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -30,19 +29,15 @@ import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.repo.api.RepositoryService; +import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConditionalSearchFilterType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectSynchronizationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestCorrelationConfirmationEvaluator extends AbstractInternalModelIntegrationTest { @@ -60,10 +55,8 @@ public class TestCorrelationConfirmationEvaluator extends AbstractInternalModelI @Autowired private ExpressionFactory expressionFactory; @Test - public void test001CorrelationOrFilter() throws Exception{ - String TEST_NAME = "test001CorrelationOrFilter"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + public void test001CorrelationOrFilter() throws Exception { + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); @@ -89,14 +82,11 @@ public void test001CorrelationOrFilter() throws Exception{ PrismObject jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); - } @Test - public void test002CorrelationMoreThanOne() throws Exception{ - String TEST_NAME = "test002CorrelationMoreThanOne"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + public void test002CorrelationMoreThanOne() throws Exception { + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); @@ -121,18 +111,13 @@ public void test002CorrelationMoreThanOne() throws Exception{ PrismObject jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); - } @Test - public void test003CorrelationWithCondition() throws Exception{ - String TEST_NAME = "test003CorrelationWithCondition"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + public void test003CorrelationWithCondition() throws Exception { + Task task = getTestTask(); OperationResult result = task.getResult(); -// importObjectFromFile(USER_JACK_FILENAME); - PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); @@ -155,14 +140,11 @@ public void test003CorrelationWithCondition() throws Exception{ PrismObject jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "jack", "Jack Sparrow", "Jack", "Sparrow"); - } @Test - public void test004CorrelationMatchCaseInsensitive() throws Exception{ - String TEST_NAME = "test004CorrelationMatchCaseInsensitive"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + public void test004CorrelationMatchCaseInsensitive() throws Exception { + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); @@ -172,24 +154,21 @@ public void test004CorrelationMatchCaseInsensitive() throws Exception{ SynchronizationContext syncCtx = createSynchronizationContext(ACCOUNT_SHADOW_JACK_DUMMY_FILE, CORRELATION_CASE_INSENSITIVE, RESOURCE_DUMMY_FILE, task, result); - try{ + try { boolean matchedUsers = evaluator.matchFocusByCorrelationRule(syncCtx, userType, result); System.out.println("matched users " + matchedUsers); AssertJUnit.assertTrue(matchedUsers); - } catch (Exception ex){ + } catch (Exception ex) { LOGGER.error("exception occured: {}", ex.getMessage(), ex); throw ex; } - } @Test - public void test005CorrelationMatchCaseInsensitive() throws Exception{ - String TEST_NAME = "test005CorrelationMatchCaseInsensitive"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + public void test005CorrelationMatchCaseInsensitive() throws Exception { + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); @@ -199,17 +178,16 @@ public void test005CorrelationMatchCaseInsensitive() throws Exception{ SynchronizationContext syncCtx = createSynchronizationContext(ACCOUNT_SHADOW_JACK_DUMMY_FILE, CORRELATION_CASE_INSENSITIVE_EMPL_NUMBER, RESOURCE_DUMMY_FILE, task, result); - try{ + try { boolean matchedUsers = evaluator.matchFocusByCorrelationRule(syncCtx, userType, result); System.out.println("matched users " + matchedUsers); AssertJUnit.assertTrue(matchedUsers); - } catch (Exception ex){ + } catch (Exception ex) { LOGGER.error("exception occured: {}", ex.getMessage(), ex); throw ex; } - } private SynchronizationContext createSynchronizationContext(File account, String correlationFilter, File resource, Task task, OperationResult result) throws SchemaException, IOException { @@ -234,15 +212,11 @@ private SynchronizationContext createSynchronizationContext(File accou return syncCtx; } - @Test - public void test006CorrelationFindCaseInsensitive() throws Exception{ - String TEST_NAME = "test006CorrelationFindCaseInsensitive"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + public void test006CorrelationFindCaseInsensitive() throws Exception { + Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject userType = repositoryService.getObject(UserType.class, USER_JACK_OID, null, result); //assert jack assertNotNull(userType); @@ -269,6 +243,5 @@ public void test006CorrelationFindCaseInsensitive() throws Exception{ PrismObject jack = matchedUsers.get(0); assertUser(jack, "c0c010c0-d34d-b33f-f00d-111111111111", "JACK", "Jack Sparrow", "Jack", "Sparrow"); - } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java index c6ba6e0e3a9..65bcd510f44 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java @@ -48,9 +48,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.SynchronizationSituationType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author semancik - */ @ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSynchronizationService extends AbstractInternalModelIntegrationTest { @@ -143,8 +140,6 @@ public void test010AddedAccountJack() throws Exception { @Test public void test020ModifyLootAbsolute() throws Exception { - final String TEST_NAME = "test020ModifyLootAbsolute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -303,8 +298,6 @@ public void test030Reconcile() throws Exception { @Test public void test039DeletedAccountJack() throws Exception { - final String TEST_NAME = "test039DeletedAccountJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -320,7 +313,7 @@ public void test039DeletedAccountJack() throws Exception { getDummyResource().deleteAccountByName(ACCOUNT_JACK_DUMMY_USERNAME); - PrismObject shadow = getShadowModelNoFetch(accountShadowJackDummyOid); + PrismObject shadow; // TODO = getShadowModelNoFetch(accountShadowJackDummyOid); shadowRepo = repositoryService.getObject(ShadowType.class, accountShadowJackDummyOid, null, result); ShadowAsserter.forShadow(shadowRepo, "repo shadow after noFetch") @@ -404,8 +397,6 @@ public void test039DeletedAccountJack() throws Exception { */ @Test public void test050AddedAccountCalypso() throws Exception { - final String TEST_NAME = "test050AddedAccountCalypso"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -454,8 +445,6 @@ public void test050AddedAccountCalypso() throws Exception { */ @Test public void test051CalypsoRecon() throws Exception { - final String TEST_NAME = "test051CalypsoRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -499,8 +488,6 @@ public void test051CalypsoRecon() throws Exception { @Test public void test100AddedAccountJack() throws Exception { - final String TEST_NAME = "test100AddedAccountJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -570,8 +557,6 @@ public void test100AddedAccountJack() throws Exception { */ @Test public void test199DeletedAccountJackTotal() throws Exception { - final String TEST_NAME = "test199DeletedAccountJackTotal"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -627,8 +612,6 @@ public void test199DeletedAccountJackTotal() throws Exception { */ @Test public void test200AddedAccountJackSchemaViolation() throws Exception { - final String TEST_NAME = "test200AddedAccountJackSchemaViolation"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -700,8 +683,6 @@ public void test200AddedAccountJackSchemaViolation() throws Exception { */ @Test public void test202UpdatedAccountJackSchemaViolation() throws Exception { - final String TEST_NAME = "test202UpdatedAccountJackSchemaViolation"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -762,8 +743,6 @@ public void test202UpdatedAccountJackSchemaViolation() throws Exception { */ @Test public void test210AssignJackDummy() throws Exception { - final String TEST_NAME = "test210AssignJackDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -810,8 +789,6 @@ public void test210AssignJackDummy() throws Exception { */ @Test public void test212AssignJackDummyLimited() throws Exception { - final String TEST_NAME = "test212AssignJackDummyLimited"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -868,8 +845,6 @@ public void test212AssignJackDummyLimited() throws Exception { */ @Test public void test214UpdatedAccountJackLimited() throws Exception { - final String TEST_NAME = "test214UpdatedAccountJackLimited"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -953,8 +928,6 @@ public void test214UpdatedAccountJackLimited() throws Exception { @Test public void test300AddedGroupPirates() throws Exception { - final String TEST_NAME = "test300AddedGroupPirates"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -989,7 +962,7 @@ public void test300AddedGroupPirates() throws Exception { assertNotNull("No focus primary delta", context.getFocusContext().getPrimaryDelta()); assertFalse("No executed focus deltas", context.getFocusContext().getExecutedDeltas().isEmpty()); - ObjectDelta userSecondaryDelta = context.getFocusContext().getExecutedDeltas().iterator().next().getObjectDelta(); + context.getFocusContext().getExecutedDeltas().iterator().next().getObjectDelta(); ResourceShadowDiscriminator rat = new ResourceShadowDiscriminator(getDummyResourceObject().getOid(), ShadowKindType.ENTITLEMENT, INTENT_GROUP, null, false); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java index 4b7b051a925..f72933cf669 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractConfiguredModelIntegrationTest.java @@ -44,9 +44,6 @@ import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -/** - * @author semancik - */ public class AbstractConfiguredModelIntegrationTest extends AbstractModelIntegrationTest { public static final File SYSTEM_CONFIGURATION_FILE = new File(COMMON_DIR, "system-configuration.xml"); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java index f02eec31ac8..e06df82704d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/AbstractInitializedModelIntegrationTest.java @@ -49,10 +49,6 @@ import javax.xml.datatype.XMLGregorianCalendar; -/** - * @author semancik - * - */ public class AbstractInitializedModelIntegrationTest extends AbstractConfiguredModelIntegrationTest { private static final int NUM_FUNCTIONAL_ORGS = 6; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java index 693be663603..04af15e9c13 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java @@ -155,8 +155,6 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test050CheckJackEnabled() throws Exception { - final String TEST_NAME = "test050CheckJackEnabled"; - // GIVEN, WHEN // this happens during test initialization when user-jack.xml is added @@ -719,7 +717,6 @@ public void test115ModifyUserJackAdministrativeStatusNull() throws Exception { Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); // WHEN modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result); @@ -727,7 +724,6 @@ public void test115ModifyUserJackAdministrativeStatusNull() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject userJack = getUser(USER_JACK_OID); display("User after change execution", userJack); @@ -799,8 +795,6 @@ public void test118ModifyJackActivationUserAndAccount() throws Exception { */ @Test public void test120ModifyUserJackAssignAccountDummyRed() throws Exception { - final String TEST_NAME = "test120ModifyUserJackAssignAccountDummyRed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -996,8 +990,6 @@ public void test139ModifyUserJackUnAssignAccountDummyRed() throws Exception { */ @Test public void test140ModifyUserJackAssignAccountDummyRed() throws Exception { - final String TEST_NAME = "test140ModifyUserJackAssignAccountDummyRed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1045,8 +1037,6 @@ public void test140ModifyUserJackAssignAccountDummyRed() throws Exception { */ @Test public void test147ModifyUserJackUnassignAccountDummyRedRaw() throws Exception { - final String TEST_NAME = "test147ModifyUserJackUnassignAccountDummyRedRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1092,8 +1082,6 @@ public void test147ModifyUserJackUnassignAccountDummyRedRaw() throws Exception { */ @Test public void test149RecomputeJack() throws Exception { - final String TEST_NAME = "test149RecomputeJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1140,8 +1128,6 @@ public void test149RecomputeJack() throws Exception { */ @Test public void test150ModifyUserJackAssignYellowAccount() throws Exception { - final String TEST_NAME = "test150ModifyUserJackAssignYellowAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1190,8 +1176,6 @@ public void test150ModifyUserJackAssignYellowAccount() throws Exception { */ @Test public void test151ReconcileJack() throws Exception { - final String TEST_NAME = "test151ReconcileJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1230,8 +1214,6 @@ public void test151ReconcileJack() throws Exception { */ @Test public void test152ModifyAccountsJackDisable() throws Exception { - final String TEST_NAME = "test152ModifyAccountsJackDisable"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1346,8 +1328,6 @@ private void checkAdminStatusFor15x(PrismObject user, boolean userStat */ @Test public void test160ModifyUserJackAssignAccountKhaki() throws Exception { - final String TEST_NAME = "test160ModifyUserJackAssignAccountKhaki"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1563,7 +1543,7 @@ public void test199DeleteUserJack() throws Exception { TestUtil.assertSuccess("executeChanges result", result); try { - PrismObject userJack = getUser(USER_JACK_OID); + getUser(USER_JACK_OID); AssertJUnit.fail("Jack is still alive!"); } catch (ObjectNotFoundException ex) { // This is OK @@ -1720,7 +1700,6 @@ public void test212SeeLargoTomorrow() throws Exception { final String TEST_NAME = "test212SeeLargoTomorrow"; // GIVEN - long startMillis = System.currentTimeMillis(); Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -1759,11 +1738,8 @@ public void test212SeeLargoTomorrow() throws Exception { */ @Test public void test213HastaLaMananaLargo() throws Exception { - final String TEST_NAME = "test213HastaLaMananaLargo"; - // GIVEN - long startMillis = System.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Let's play with the clock, move the time forward 20 days @@ -1931,8 +1907,6 @@ public void test231JackRecomputeReconcile() throws Exception { */ @Test public void test240AddUserRappDraft() throws Exception { - final String TEST_NAME = "test240AddUserRappDraft"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1988,8 +1962,6 @@ public void test240AddUserRappDraft() throws Exception { */ @Test public void test241RecomputeRappDraft() throws Exception { - final String TEST_NAME = "test240AddUserRappDraft"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2030,8 +2002,6 @@ public void test241RecomputeRappDraft() throws Exception { */ @Test public void test242RappAssignCaptain() throws Exception { - final String TEST_NAME = "test242RappAssignCaptain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2067,8 +2037,6 @@ public void test242RappAssignCaptain() throws Exception { */ @Test public void test245ActivateRapp() throws Exception { - final String TEST_NAME = "test245ActivateRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2109,8 +2077,6 @@ public void test245ActivateRapp() throws Exception { */ @Test public void test248DeactivateRapp() throws Exception { - final String TEST_NAME = "test248DeactivateRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2145,8 +2111,6 @@ public void test248DeactivateRapp() throws Exception { */ @Test public void test249DeleteUserRapp() throws Exception { - final String TEST_NAME = "test249DeleteUserRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2169,12 +2133,7 @@ public void test249DeleteUserRapp() throws Exception { */ @Test public void test300AddDummyGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test300AddDummyGreenAccountMancomb"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - DummyAccount account = new DummyAccount(ACCOUNT_MANCOMB_DUMMY_USERNAME); account.setEnabled(true); account.setValidFrom(ACCOUNT_MANCOMB_VALID_FROM_DATE); @@ -2209,10 +2168,7 @@ public void test300AddDummyGreenAccountMancomb() throws Exception { */ @Test public void test310ImportAccountsFromDummyGreen() throws Exception { - final String TEST_NAME = "test310ImportAccountsFromDummyGreen"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java index 08282141cc0..f7a5873256f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java @@ -1213,7 +1213,6 @@ public void test800ImportValidityScannerTask() throws Exception { final String TEST_NAME = "test800ImportValidityScannerTask"; // GIVEN - TestValidityRecomputeTask.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestOptimizingTriggerCreator.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestOptimizingTriggerCreator.java index e51648774c6..733020dc0df 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestOptimizingTriggerCreator.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestOptimizingTriggerCreator.java @@ -32,8 +32,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100CreateThreeTriggers() throws Exception { - final String TEST_NAME = "test100CreateThreeTriggers"; - OptimizingTriggerCreator creator = libraryMidpointFunctions.getOptimizingTriggerCreator(60000, 2000); boolean first = creator.createForNamedUser(USER_JACK_USERNAME); boolean second = creator.createForNamedUser(USER_JACK_USERNAME); @@ -48,9 +46,6 @@ public void test100CreateThreeTriggers() throws Exception { @Test public void test110CreateTriggersWithUserDeletion() throws Exception { - final String TEST_NAME = "test110CreateTriggersWithUserDeletion"; - - TestTriggerTask.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -80,8 +75,6 @@ public void test110CreateTriggersWithUserDeletion() throws Exception { @Test public void test200CreateThreeTriggersByOid() throws Exception { - final String TEST_NAME = "test200CreateThreeTriggersByOid"; - OptimizingTriggerCreator creator = libraryMidpointFunctions.getOptimizingTriggerCreator(60000, 2000); boolean first = creator.createForObject(UserType.class, USER_BARBOSSA_OID); boolean second = creator.createForObject(UserType.class, USER_BARBOSSA_OID); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTriggerTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTriggerTask.java index a7c271e6a52..dc0db608551 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTriggerTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTriggerTask.java @@ -52,9 +52,6 @@ public class TestTriggerTask extends AbstractInitializedModelIntegrationTest { private MockTriggerHandler testTriggerHandler; private MockMultipleTriggersHandler testMultipleTriggersHandler; - private XMLGregorianCalendar drakeValidFrom; - private XMLGregorianCalendar drakeValidTo; - @Autowired private TriggerHandlerRegistry triggerHandlerRegistry; @@ -66,7 +63,6 @@ protected ConflictResolutionActionType getDefaultConflictResolutionAction() { @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - // TODO Auto-generated method stub super.initSystem(initTask, initResult); testTriggerHandler = new MockTriggerHandler(); @@ -78,13 +74,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ImportScannerTask() throws Exception { - final String TEST_NAME = "test100ImportScannerTask"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - // Make sure there is an object with a trigger set to a long time ago. // That trigger should be invoked on first run. addTrigger(USER_JACK_OID, LONG_LONG_TIME_AGO, MockTriggerHandler.HANDLER_URI); @@ -112,12 +102,7 @@ public void test100ImportScannerTask() throws Exception { @Test public void test105NoTrigger() throws Exception { - final String TEST_NAME = "test105NoTrigger"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -140,12 +125,7 @@ public void test105NoTrigger() throws Exception { @Test public void test110TriggerCalledAgain() throws Exception { - final String TEST_NAME = "test110TriggerCalledAgain"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -171,12 +151,7 @@ public void test110TriggerCalledAgain() throws Exception { @Test public void test120TwoTriggers() throws Exception { - final String TEST_NAME = "test120TwoTriggers"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -205,12 +180,7 @@ public void test120TwoTriggers() throws Exception { @Test public void test130TwoTriggersSame() throws Exception { - final String TEST_NAME = "test130TwoTriggersSame"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -235,12 +205,7 @@ public void test130TwoTriggersSame() throws Exception { @Test public void test135TwoTriggersSamePlusOne() throws Exception { - final String TEST_NAME = "test135TwoTriggersSamePlusOne"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -267,12 +232,7 @@ public void test135TwoTriggersSamePlusOne() throws Exception { @Test public void test140TwoTriggersSameAggregable() throws Exception { - final String TEST_NAME = "test140TwoTriggersSameAggregable"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -298,19 +258,14 @@ public void test140TwoTriggersSameAggregable() throws Exception { @Test public void test145TwoTriggersSamePlusOneAggregable() throws Exception { - final String TEST_NAME = "test145TwoTriggersSamePlusOneAggregable"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testMultipleTriggersHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); XMLGregorianCalendar startCalPlus5ms = XmlTypeConverter.createXMLGregorianCalendar(startCal); startCalPlus5ms.add(XmlTypeConverter.createDuration(5L)); - addTriggers(USER_JACK_OID, Arrays.asList(startCal, startCal, startCalPlus5ms), MockMultipleTriggersHandler.HANDLER_URI, - true); + addTriggers(USER_JACK_OID, Arrays.asList(startCal, startCal, startCalPlus5ms), + MockMultipleTriggersHandler.HANDLER_URI, true); /// WHEN when(); @@ -332,12 +287,6 @@ public void test145TwoTriggersSamePlusOneAggregable() throws Exception { @Test public void test147TwoTriggersIdempotent() throws Exception { - final String TEST_NAME = "test147TwoTriggersIdempotent"; - - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); testTriggerHandler.setIdempotent(true); @@ -369,12 +318,6 @@ public void test147TwoTriggersIdempotent() throws Exception { @Test public void test150NoTriggerAgain() throws Exception { - final String TEST_NAME = "test115NoTriggerAgain"; - - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -398,10 +341,7 @@ public void test150NoTriggerAgain() throws Exception { // MID-4610 @Test public void test160TwoTriggersFirstFails() throws Exception { - final String TEST_NAME = "test160TwoTriggersFirstFails"; - - // GIVEN - TestTriggerTask.class.getName(); + given(); Task task = getTestTask(); OperationResult result = task.getResult(); testTriggerHandler.reset(); @@ -413,13 +353,10 @@ public void test160TwoTriggersFirstFails() throws Exception { testTriggerHandler.setFailOnNextInvocation(true); - /// WHEN when(); waitForTaskNextRun(TASK_TRIGGER_SCANNER_OID, true, 10000); - // THEN then(); - XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); assertNotNull("Trigger was not called", testTriggerHandler.getLastObject()); @@ -455,12 +392,7 @@ public void test160TwoTriggersFirstFails() throws Exception { @Test public void test200TwoDistantTriggers() throws Exception { - final String TEST_NAME = "test200TwoDistantTriggers"; - // GIVEN - TestTriggerTask.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); testTriggerHandler.reset(); XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); @@ -488,10 +420,7 @@ public void test200TwoDistantTriggers() throws Exception { // MID-4474 @Test public void test210InterruptedScanner() throws Exception { - final String TEST_NAME = "test210InterruptedScanner"; - // GIVEN - TestTriggerTask.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); testTriggerHandler.reset(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestVolatility.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestVolatility.java index 7fe4da9d272..f84eab55123 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestVolatility.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestVolatility.java @@ -40,9 +40,6 @@ /** * Tests for MID-2436 (volatile attributes). - * - * @author mederly - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -91,32 +88,16 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ImportLiveSyncTaskDummyHr() throws Exception { - final String TEST_NAME = "test100ImportLiveSyncTaskDummyHr"; - - // GIVEN - TestVolatility.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); importSyncTask(); - // THEN then(); - waitForSyncTaskStart(); } @Test public void test110AddDummyHrAccountMancomb() throws Exception { - final String TEST_NAME = "test110AddDummyHrAccountMancomb"; - // GIVEN - TestVolatility.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - // Preconditions //assertUsers(5); @@ -174,14 +155,6 @@ public void test110AddDummyHrAccountMancomb() throws Exception { @Test public void test120UpdateDummyHrAccountMancomb() throws Exception { - final String TEST_NAME = "test120UpdateDummyHrAccountMancomb"; - - // GIVEN - TestVolatility.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); DummyAccount account = getDummyResource(RESOURCE_DUMMY_HR_NAME).getAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); account.replaceAttributeValue(DummyAccount.ATTR_FULLNAME_NAME, "Sir Mancomb Seepgood"); @@ -191,9 +164,7 @@ public void test120UpdateDummyHrAccountMancomb() throws Exception { // Make sure we have steady state waitForSyncTaskNextRun(); - // THEN then(); - PrismObject accountMancombHr = findAccountByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_HR_NAME)); display("Account mancomb on HR", accountMancombHr); @@ -240,10 +211,7 @@ public void test120UpdateDummyHrAccountMancomb() throws Exception { @Test public void test200ModifyGuybrushAssignAccount() throws Exception { - final String TEST_NAME = "test200ModifyGuybrushAssignAccount"; - // GIVEN - TestVolatility.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -293,10 +261,7 @@ public void test200ModifyGuybrushAssignAccount() throws Exception { @Test public void test300AddLargo() throws Exception { - final String TEST_NAME = "test300AddLargo"; - // GIVEN - TestVolatility.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -348,10 +313,7 @@ public void test300AddLargo() throws Exception { */ @Test public void test400AddHerman() throws Exception { - final String TEST_NAME = "test400AddHerman"; - // GIVEN - TestVolatility.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -390,10 +352,7 @@ public void test400AddHerman() throws Exception { */ @Test public void test402ModifyHermanMonster() throws Exception { - final String TEST_NAME = "test402ModifyHermanMonster"; - // GIVEN - TestVolatility.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java index 0b666c1e6e1..3c87a3e8a2f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java @@ -7,6 +7,17 @@ package com.evolveum.midpoint.model.intest.async; +import java.io.File; +import java.io.FileReader; +import java.io.IOException; +import java.nio.charset.StandardCharsets; + +import org.apache.commons.io.IOUtils; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.ResourceShadowDiscriminator; @@ -15,23 +26,13 @@ import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.io.IOUtils; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.io.File; -import java.io.FileReader; -import java.io.IOException; -import java.nio.charset.StandardCharsets; /** - * Tests async updates using Grouper JSON messages. - * - * Currently uses caching. + * Tests async updates using Grouper JSON messages. + *

+ * Currently uses caching. */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestAsyncUpdateGrouperJson extends AbstractInitializedModelIntegrationTest { @@ -75,24 +76,18 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { final String TEST_NAME = "test000Sanity"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult testResultGrouper = modelService.testResource(RESOURCE_GROUPER_OID, task); TestUtil.assertSuccess(testResultGrouper); } - private Task createTestTask(String TEST_NAME) { - TestAsyncUpdateGrouperJson.class.getName(); - return getTestTask(); - } - /** * The first MEMBERSHIP_ADD event for banderson (supergroup) */ @Test public void test100AddAnderson() throws Exception { - final String TEST_NAME = "test100AddAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -113,15 +108,15 @@ public void test100AddAnderson() throws Exception { assertUserAfterByUsername(BANDERSON_USERNAME) .displayWithProjections() .links() - .single() - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - // .assertIntent(GROUPER_USER_INTENT) - .assertResource(RESOURCE_GROUPER_OID) - .end() - .end() - .end() + .single() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + // .assertIntent(GROUPER_USER_INTENT) + .assertResource(RESOURCE_GROUPER_OID) + .end() + .end() + .end() .assertOrganizationalUnits(); } @@ -137,8 +132,7 @@ private AsyncUpdateMessageType getAmqp091Message(File file) throws IOException { */ @Test public void test110AddAlumniAndStaff() throws Exception { - final String TEST_NAME = "test110AddAlumniAndStaff"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -160,22 +154,22 @@ public void test110AddAlumniAndStaff() throws Exception { assertOrgByName(ALUMNI_NAME, "after") .displayWithProjections() .links() - .single() - .resolveTarget() - .display() - .assertKind(ShadowKindType.ENTITLEMENT) + .single() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ENTITLEMENT) // .assertIntent(GROUPER_GROUP_INTENT) - .assertResource(RESOURCE_GROUPER_OID); + .assertResource(RESOURCE_GROUPER_OID); assertOrgByName(STAFF_NAME, "after") .displayWithProjections() .links() - .single() - .resolveTarget() - .display() - .assertKind(ShadowKindType.ENTITLEMENT) + .single() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ENTITLEMENT) // .assertIntent(GROUPER_GROUP_INTENT) - .assertResource(RESOURCE_GROUPER_OID); + .assertResource(RESOURCE_GROUPER_OID); } /** @@ -183,8 +177,7 @@ public void test110AddAlumniAndStaff() throws Exception { */ @Test public void test200AddAlumniForAnderson() throws Exception { - final String TEST_NAME = "test200AddAlumniForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -205,15 +198,15 @@ public void test200AddAlumniForAnderson() throws Exception { assertUserAfterByUsername(BANDERSON_USERNAME) .displayWithProjections() .links() - .single() - .resolveTarget() - .assertKind(ShadowKindType.ACCOUNT) - // .assertIntent(GROUPER_USER_INTENT) - .assertResource(RESOURCE_GROUPER_OID) - .display("shadow after") - .end() - .end() - .end() + .single() + .resolveTarget() + .assertKind(ShadowKindType.ACCOUNT) + // .assertIntent(GROUPER_USER_INTENT) + .assertResource(RESOURCE_GROUPER_OID) + .display("shadow after") + .end() + .end() + .end() .assertOrganizationalUnits(ALUMNI_NAME); } @@ -222,8 +215,7 @@ public void test200AddAlumniForAnderson() throws Exception { */ @Test public void test210AddStaffForAnderson() throws Exception { - final String TEST_NAME = "test210AddStaffForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -244,15 +236,15 @@ public void test210AddStaffForAnderson() throws Exception { assertUserAfterByUsername(BANDERSON_USERNAME) .displayWithProjections() .links() - .single() - .resolveTarget() - .display("shadow after") - .assertKind(ShadowKindType.ACCOUNT) + .single() + .resolveTarget() + .display("shadow after") + .assertKind(ShadowKindType.ACCOUNT) // .assertIntent(GROUPER_USER_INTENT) - .assertResource(RESOURCE_GROUPER_OID) - .end() - .end() - .end() + .assertResource(RESOURCE_GROUPER_OID) + .end() + .end() + .end() .assertOrganizationalUnits(ALUMNI_NAME, STAFF_NAME); } @@ -261,8 +253,7 @@ public void test210AddStaffForAnderson() throws Exception { */ @Test public void test220AddAlumniForLewis() throws Exception { - final String TEST_NAME = "test220AddAlumniForLewis"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -283,15 +274,15 @@ public void test220AddAlumniForLewis() throws Exception { assertUserAfterByUsername(JLEWIS685_USERNAME) .displayWithProjections() .links() - .single() - .resolveTarget() - .display("shadow after") - .assertKind(ShadowKindType.ACCOUNT) + .single() + .resolveTarget() + .display("shadow after") + .assertKind(ShadowKindType.ACCOUNT) // .assertIntent(GROUPER_USER_INTENT) - .assertResource(RESOURCE_GROUPER_OID) - .end() - .end() - .end() + .assertResource(RESOURCE_GROUPER_OID) + .end() + .end() + .end() .assertOrganizationalUnits(ALUMNI_NAME); } @@ -300,8 +291,7 @@ public void test220AddAlumniForLewis() throws Exception { */ @Test public void test230AddLewis() throws Exception { - final String TEST_NAME = "test230AddLewis"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -322,15 +312,15 @@ public void test230AddLewis() throws Exception { assertUserAfterByUsername(JLEWIS685_USERNAME) .displayWithProjections() .links() - .single() - .resolveTarget() - .display("shadow after") - .assertKind(ShadowKindType.ACCOUNT) + .single() + .resolveTarget() + .display("shadow after") + .assertKind(ShadowKindType.ACCOUNT) // .assertIntent(GROUPER_USER_INTENT) - .assertResource(RESOURCE_GROUPER_OID) - .end() - .end() - .end() + .assertResource(RESOURCE_GROUPER_OID) + .end() + .end() + .end() .assertOrganizationalUnits(ALUMNI_NAME); } @@ -339,8 +329,7 @@ public void test230AddLewis() throws Exception { */ @Test public void test240AddStaffForAnderson() throws Exception { - final String TEST_NAME = "test240AddStaffForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -361,15 +350,15 @@ public void test240AddStaffForAnderson() throws Exception { assertUserAfterByUsername(BANDERSON_USERNAME) .displayWithProjections() .links() - .single() - .resolveTarget() - .display("shadow after") - .assertKind(ShadowKindType.ACCOUNT) + .single() + .resolveTarget() + .display("shadow after") + .assertKind(ShadowKindType.ACCOUNT) // .assertIntent(GROUPER_USER_INTENT) - .assertResource(RESOURCE_GROUPER_OID) - .end() - .end() - .end() + .assertResource(RESOURCE_GROUPER_OID) + .end() + .end() + .end() .assertOrganizationalUnits(ALUMNI_NAME, STAFF_NAME); } @@ -378,8 +367,7 @@ public void test240AddStaffForAnderson() throws Exception { */ @Test public void test250DeleteAlumniForAnderson() throws Exception { - final String TEST_NAME = "test250DeleteAlumniForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -400,15 +388,15 @@ public void test250DeleteAlumniForAnderson() throws Exception { assertUserAfterByUsername(BANDERSON_USERNAME) .displayWithProjections() .links() - .single() - .resolveTarget() - .display("shadow after") - .assertKind(ShadowKindType.ACCOUNT) + .single() + .resolveTarget() + .display("shadow after") + .assertKind(ShadowKindType.ACCOUNT) // .assertIntent(GROUPER_USER_INTENT) - .assertResource(RESOURCE_GROUPER_OID) - .end() - .end() - .end() + .assertResource(RESOURCE_GROUPER_OID) + .end() + .end() + .end() .assertOrganizationalUnits(STAFF_NAME); } @@ -417,8 +405,7 @@ public void test250DeleteAlumniForAnderson() throws Exception { */ @Test public void test310DeleteStaff() throws Exception { - final String TEST_NAME = "test310DeleteStaff"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiAccount.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiAccount.java index 0478db721c0..1e3314f83be 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiAccount.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiAccount.java @@ -6,22 +6,16 @@ */ package com.evolveum.midpoint.model.intest.multi; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; - import java.io.File; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; import com.evolveum.icf.dummy.resource.DummyAccount; -import com.evolveum.midpoint.model.intest.sync.AbstractSynchronizationStoryTest; +import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; @@ -32,12 +26,12 @@ /** * Test multiple accounts with the same resource+kind+intent. - * + *

* MID-3542 * * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMultiAccount extends AbstractInitializedModelIntegrationTest { @@ -67,15 +61,10 @@ public class TestMultiAccount extends AbstractInitializedModelIntegrationTest { private static final String INTENT_ADMIN = "admin"; - private String accountPaulOid; private String accountMuaddibOid; private String accountDukeOid; - private String accountMahdiOid; - - private String userPaulOid; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -90,10 +79,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test010ImportAccountsFromDummyMultiGreen() throws Exception { - final String TEST_NAME = "test010ImportAccountsFromDummyMultiGreen"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -116,10 +102,7 @@ public void test010ImportAccountsFromDummyMultiGreen() throws Exception { */ @Test public void test020ImportPaulAtreides() throws Exception { - final String TEST_NAME = "test020ImportPaulAtreides"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -141,16 +124,16 @@ public void test020ImportPaulAtreides() throws Exception { then(); accountPaulOid = assertUserAfterByUsername(ACCOUNT_PAUL_ATREIDES_USERNAME) - .displayWithProjections() - .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) - .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) - .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME) - .singleLink() + .displayWithProjections() + .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) + .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) + .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME) + .singleLink() .resolveTarget() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTagIsOid() - .getOid(); + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTagIsOid() + .getOid(); assertUsers(getNumberOfUsers() + 1); @@ -161,10 +144,7 @@ public void test020ImportPaulAtreides() throws Exception { */ @Test public void test100ImportMuadDib() throws Exception { - final String TEST_NAME = "test100ImportMuadDib"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -185,30 +165,29 @@ public void test100ImportMuadDib() throws Exception { then(); accountMuaddibOid = assertUserAfterByUsername(ACCOUNT_PAUL_ATREIDES_USERNAME) - .displayWithProjections() - .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) - .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) - .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME, ACCOUNT_MUAD_DIB_FULL_NAME) - .links() + .displayWithProjections() + .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) + .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) + .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME, ACCOUNT_MUAD_DIB_FULL_NAME) + .links() .assertLinks(2) .link(accountPaulOid) - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTag(accountPaulOid) - .end() - .end() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTag(accountPaulOid) + .end() + .end() .by() - .notTags(accountPaulOid) + .notTags(accountPaulOid) .find() - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTagIsOid() - .getOid(); - + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTagIsOid() + .getOid(); assertUsers(getNumberOfUsers() + 1); @@ -216,14 +195,11 @@ public void test100ImportMuadDib() throws Exception { @Test public void test102ReconcileUserPaul() throws Exception { - final String TEST_NAME = "test102ReconcileUserPaul"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); - userPaulOid = findUserByUsername(ACCOUNT_PAUL_ATREIDES_USERNAME).getOid(); + String userPaulOid = findUserByUsername(ACCOUNT_PAUL_ATREIDES_USERNAME).getOid(); // WHEN when(); @@ -233,30 +209,30 @@ public void test102ReconcileUserPaul() throws Exception { then(); accountMuaddibOid = assertUserAfter(userPaulOid) - .displayWithProjections() - .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) - .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) - // TODO - .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME, ACCOUNT_MUAD_DIB_FULL_NAME) - .links() + .displayWithProjections() + .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) + .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) + // TODO + .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME, ACCOUNT_MUAD_DIB_FULL_NAME) + .links() .assertLinks(2) .link(accountPaulOid) - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTag(accountPaulOid) - .end() - .end() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTag(accountPaulOid) + .end() + .end() .by() - .notTags(accountPaulOid) + .notTags(accountPaulOid) .find() - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTagIsOid() - .getOid(); + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTagIsOid() + .getOid(); assertUsers(getNumberOfUsers() + 1); @@ -269,10 +245,7 @@ public void test102ReconcileUserPaul() throws Exception { */ @Test public void test200ImportDuke() throws Exception { - final String TEST_NAME = "test200ImportDuke"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -294,39 +267,38 @@ public void test200ImportDuke() throws Exception { then(); accountDukeOid = assertUserAfterByUsername(ACCOUNT_PAUL_ATREIDES_USERNAME) - .displayWithProjections() - .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) - .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) - // TODO + .displayWithProjections() + .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) + .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) + // TODO // .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME, ACCOUNT_MUAD_DIB_FULL_NAME) - .links() + .links() .assertLinks(3) .link(accountPaulOid) - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTag(accountPaulOid) - .end() - .end() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTag(accountPaulOid) + .end() + .end() .link(accountMuaddibOid) - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTag(accountMuaddibOid) - .end() - .end() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTag(accountMuaddibOid) + .end() + .end() .by() - .notTags(accountPaulOid, accountMuaddibOid) + .notTags(accountPaulOid, accountMuaddibOid) .find() - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(INTENT_ADMIN) - .assertTag(ACCOUNT_DUKE_TITLE) - .getOid(); - + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(INTENT_ADMIN) + .assertTag(ACCOUNT_DUKE_TITLE) + .getOid(); assertUsers(getNumberOfUsers() + 1); @@ -337,10 +309,7 @@ public void test200ImportDuke() throws Exception { */ @Test public void test210ImportMahdi() throws Exception { - final String TEST_NAME = "test210ImportMahdi"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -361,48 +330,49 @@ public void test210ImportMahdi() throws Exception { // THEN then(); - accountMahdiOid = assertUserAfterByUsername(ACCOUNT_PAUL_ATREIDES_USERNAME) - .displayWithProjections() - .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) - .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) - // TODO + // TODO + // .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME, ACCOUNT_MUAD_DIB_FULL_NAME) + String accountMahdiOid = assertUserAfterByUsername(ACCOUNT_PAUL_ATREIDES_USERNAME) + .displayWithProjections() + .assertFullName(ACCOUNT_PAUL_ATREIDES_FULL_NAME) + .assertEmployeeNumber(ACCOUNT_PAUL_ATREIDES_ID) + // TODO // .assertOrganizationalUnits(ACCOUNT_PAUL_ATREIDES_FULL_NAME, ACCOUNT_MUAD_DIB_FULL_NAME) - .links() + .links() .assertLinks(4) .link(accountPaulOid) - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTag(accountPaulOid) - .end() - .end() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTag(accountPaulOid) + .end() + .end() .link(accountMuaddibOid) - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(SchemaConstants.INTENT_DEFAULT) - .assertTag(accountMuaddibOid) - .end() - .end() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(SchemaConstants.INTENT_DEFAULT) + .assertTag(accountMuaddibOid) + .end() + .end() .link(accountDukeOid) - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(INTENT_ADMIN) - .assertTag(ACCOUNT_DUKE_TITLE) - .end() - .end() + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(INTENT_ADMIN) + .assertTag(ACCOUNT_DUKE_TITLE) + .end() + .end() .by() - .notTags(accountPaulOid, accountMuaddibOid, ACCOUNT_DUKE_TITLE) + .notTags(accountPaulOid, accountMuaddibOid, ACCOUNT_DUKE_TITLE) .find() - .resolveTarget() - .display() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(INTENT_ADMIN) - .assertTag(ACCOUNT_MAHDI_TITLE) - .getOid(); - + .resolveTarget() + .display() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(INTENT_ADMIN) + .assertTag(ACCOUNT_MAHDI_TITLE) + .getOid(); assertUsers(getNumberOfUsers() + 1); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/AbstractPasswordTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/AbstractPasswordTest.java index f6084f01349..d0c686b3e11 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/AbstractPasswordTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/password/AbstractPasswordTest.java @@ -267,7 +267,6 @@ public void test060CheckJackPasswordModelInteraction() throws Exception { } // GIVEN - AbstractPasswordTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -611,7 +610,6 @@ public void test122ModifyAccountUglyJackPasswordBad() throws Exception { prepareTest(); // GIVEN - AbstractPasswordTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -749,7 +747,6 @@ public void test130JackAssignAccountDummyBlack() throws Exception { @Test public void test132ModifyAccountBlackJackPasswordBad() throws Exception { // GIVEN - AbstractPasswordTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); prepareTest(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java index 5469a6bd64e..93e0cf3e7e8 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java @@ -53,9 +53,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.EvaluationTimeType; -/** - * @author semancik - */ @ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRbac extends AbstractRbacTest { @@ -242,7 +239,7 @@ public void test110UnAssignRolePirate() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - assertAssignedNoRole(userAfter, task, result); + assertAssignedNoRole(userAfter); assertRoleMembershipRef(userAfter); assertDelegatedRef(userAfter); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); @@ -1674,7 +1671,7 @@ public void test549JackUnassignRoleWannabe() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - assertNotAssignedRole(userAfter, ROLE_WANNABE_OID, task, result); + assertNotAssignedRole(userAfter, ROLE_WANNABE_OID, result); assertRoleMembershipRef(userAfter); assertDelegatedRef(userAfter); @@ -2533,7 +2530,7 @@ public void test709JackUnAssignRoleJudge() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } @@ -2641,7 +2638,7 @@ public void test719JackUnAssignRoleEmpty() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } @@ -2699,7 +2696,7 @@ public void test729JackUnassignRoleGovernorTenantRef() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); assertAssignees(ROLE_GOVERNOR_OID, 0); @@ -2796,7 +2793,7 @@ public void test759JackUnassignRoleOmnimanager() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - assertNotAssignedRole(userAfter, ROLE_PROJECT_OMNINAMAGER_OID, task, result); + assertNotAssignedRole(userAfter, ROLE_PROJECT_OMNINAMAGER_OID, result); assertHasNoOrg(userAfter); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java index bbad6e9095e..3366ff02c13 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java @@ -210,7 +210,7 @@ public void test110SimpleExclusion1() throws Exception { unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } /** @@ -237,7 +237,7 @@ public void test120SimpleExclusion2() throws Exception { } unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -261,7 +261,7 @@ public void test130SimpleExclusionBoth1() throws Exception { System.out.println("Got expected exception: " + e.getMessage()); } - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -285,7 +285,7 @@ public void test140SimpleExclusionBoth2() throws Exception { System.out.println("Got expected exception: " + e.getMessage()); } - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -309,7 +309,7 @@ public void test150SimpleExclusionBothBidirectional1() throws Exception { System.out.println("Got expected exception: " + e.getMessage()); } - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -333,7 +333,7 @@ public void test160SimpleExclusionBothBidirectional2() throws Exception { System.out.println("Got expected exception: " + e.getMessage()); } - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -354,7 +354,7 @@ public void test171SimpleExclusion1WithPolicyException() throws Exception { unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -375,7 +375,7 @@ public void test172SimpleExclusion2WithPolicyException() throws Exception { unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -396,7 +396,7 @@ public void test173SimpleExclusion3WithPolicyException() throws Exception { unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -417,7 +417,7 @@ public void test174SimpleExclusion4WithPolicyException() throws Exception { unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } /** @@ -453,7 +453,7 @@ public void test180JudgeExceptionalPirateAndThief() throws Exception { unassignRole(USER_JACK_OID, ROLE_JUDGE_OID, task, result); unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, null, getJudgeExceptionBlock(ROLE_PIRATE_NAME), task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } private Consumer getJudgeExceptionBlock(String excludedRoleName) { @@ -484,7 +484,7 @@ public void test190DifferentRelations() throws Exception { unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, task, result); } - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -507,7 +507,7 @@ public void test193BothRelationsApprover() throws Exception { unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, SchemaConstants.ORG_APPROVER, task, result); } - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -534,7 +534,7 @@ public void test194MemberAndManager() throws Exception { unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, SchemaConstants.ORG_DEFAULT, task, result); } - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } /** @@ -1760,7 +1760,7 @@ public void test950JackSelfExclusion() throws Exception { unassignRole(USER_JACK_OID, ROLE_SELF_EXCLUSION_OID, SchemaConstants.ORG_APPROVER, task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } @Test @@ -1789,7 +1789,7 @@ public void test952JackSelfExclusionManagerMember() throws Exception { unassignRole(USER_JACK_OID, ROLE_SELF_EXCLUSION_MANAGER_MEMBER_OID, SchemaConstants.ORG_DEFAULT, task, result); - assertAssignedNoRole(USER_JACK_OID, task, result); + assertAssignedNoRole(USER_JACK_OID, result); } // MID-5207 diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractInboundSyncTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractInboundSyncTest.java index 39693ba4aee..ab4ad95900d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractInboundSyncTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractInboundSyncTest.java @@ -13,7 +13,6 @@ import java.io.FileNotFoundException; import java.util.Collections; import java.util.Date; - import javax.xml.datatype.XMLGregorianCalendar; import org.springframework.test.annotation.DirtiesContext; @@ -31,17 +30,12 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SynchronizationSituationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractInboundSyncTest extends AbstractInitializedModelIntegrationTest { @@ -53,16 +47,12 @@ public abstract class AbstractInboundSyncTest extends AbstractInitializedModelIn protected static final File TASK_RECON_DUMMY_EMERALD_FILE = new File(TEST_DIR, "task-dummy-emerald-recon.xml"); protected static final String TASK_RECON_DUMMY_EMERALD_OID = "10000000-0000-0000-5656-56560000e404"; - protected static final String ACCOUNT_WALLY_DUMMY_USERNAME = "wally"; protected static final String ACCOUNT_MANCOMB_DUMMY_USERNAME = "mancomb"; protected static final Date ACCOUNT_MANCOMB_VALID_FROM_DATE = MiscUtil.asDate(2011, 2, 3, 4, 5, 6); protected static final Date ACCOUNT_MANCOMB_VALID_TO_DATE = MiscUtil.asDate(2066, 5, 4, 3, 2, 1); protected static final String ACCOUNT_POSIXUSER_DUMMY_USERNAME = "posixuser"; - protected static String userWallyOid; - - protected boolean allwaysCheckTimestamp = false; protected long timeBeforeSync; @Override @@ -85,38 +75,18 @@ protected int getWaitTimeout() { return DEFAULT_TASK_WAIT_TIMEOUT; } - protected int getNumberOfExtraDummyUsers() { - return 0; - } - - @Test public void test100ImportLiveSyncTaskDummyEmerald() throws Exception { - final String TEST_NAME = "test100ImportLiveSyncTaskDummyEmerald"; - - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); importSyncTask(resourceDummyEmerald); - // THEN then(); - waitForSyncTaskStart(resourceDummyEmerald); } @Test public void test110AddDummyEmeraldAccountMancomb() throws Exception { - final String TEST_NAME = "test110AddDummyEmeraldAccountMancomb"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -169,12 +139,7 @@ public void test110AddDummyEmeraldAccountMancomb() throws Exception { @Test public void test120ModifyDummyEmeraldAccountMancombSeepbad() throws Exception { - final String TEST_NAME = "test120ModifyDummyEmeraldAccountMancombSeepbad"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -224,12 +189,7 @@ public void test120ModifyDummyEmeraldAccountMancombSeepbad() throws Exception { @Test public void test122ModifyDummyEmeraldAccountMancombSeepNULL() throws Exception { - final String TEST_NAME = "test122ModifyDummyEmeraldAccountMancombSeepNULL"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -279,12 +239,7 @@ public void test122ModifyDummyEmeraldAccountMancombSeepNULL() throws Exception { @Test public void test124ModifyDummyEmeraldAccountMancombSeepevil() throws Exception { - final String TEST_NAME = "test124ModifyDummyEmeraldAccountMancombSeepevil"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -334,12 +289,7 @@ public void test124ModifyDummyEmeraldAccountMancombSeepevil() throws Exception { @Test public void test126ModifyDummyEmeraldAccountMancombTitlePirate() throws Exception { - final String TEST_NAME = "test126ModifyDummyEmeraldAccountMancombTitlePirate"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -390,12 +340,7 @@ public void test126ModifyDummyEmeraldAccountMancombTitlePirate() throws Exceptio @Test public void test127ModifyDummyEmeraldAccountMancombTitlePirateNull() throws Exception { - final String TEST_NAME = "test127ModifyDummyEmeraldAccountMancombTitlePirateNull"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -446,12 +391,7 @@ public void test127ModifyDummyEmeraldAccountMancombTitlePirateNull() throws Exce @Test public void test129ModifyDummyEmeraldAccountMancombSeepgood() throws Exception { - final String TEST_NAME = "test129ModifyDummyEmeraldAccountMancombSeepgood"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -499,7 +439,6 @@ public void test129ModifyDummyEmeraldAccountMancombSeepgood() throws Exception { notificationManager.setDisabled(true); } - @Test public void test180NoChange() throws Exception { // default = no op @@ -511,12 +450,7 @@ public void test180NoChange() throws Exception { @Test public void test300AddDummyEmeraldAccountPosixUser() throws Exception { - final String TEST_NAME = "test300AddDummyEmeraldAccountPosixUser"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -569,12 +503,7 @@ public void test300AddDummyEmeraldAccountPosixUser() throws Exception { @Test public void test310ModifyDummyEmeraldAccountPosixUserUidNumber() throws Exception { - final String TEST_NAME = "test310ModifyDummyEmeraldAccountPosixUserUidNumber"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -618,7 +547,6 @@ public void test310ModifyDummyEmeraldAccountPosixUserUidNumber() throws Exceptio // TODO create and test inbounds for uid and gid numbers; also other attributes } - protected void waitForSyncTaskStart(PrismObject resource) throws Exception { waitForTaskStart(getSyncTaskOid(resource), false, getWaitTimeout()); } @@ -627,7 +555,6 @@ protected void waitForSyncTaskNextRun(PrismObject resource) throws waitForTaskNextRunAssertSuccess(getSyncTaskOid(resource), false, getWaitTimeout()); } - protected void rememberTimeBeforeSync() { timeBeforeSync = System.currentTimeMillis(); } @@ -635,11 +562,11 @@ protected void rememberTimeBeforeSync() { protected void assertShadowOperationalData(PrismObject shadow, SynchronizationSituationType expectedSituation) { ShadowType shadowType = shadow.asObjectable(); SynchronizationSituationType actualSituation = shadowType.getSynchronizationSituation(); - assertEquals("Wrong situation in shadow "+shadow, expectedSituation, actualSituation); + assertEquals("Wrong situation in shadow " + shadow, expectedSituation, actualSituation); XMLGregorianCalendar actualTimestampCal = shadowType.getSynchronizationTimestamp(); - assert actualTimestampCal != null : "No synchronization timestamp in shadow "+shadow; + assert actualTimestampCal != null : "No synchronization timestamp in shadow " + shadow; long actualTimestamp = XmlTypeConverter.toMillis(actualTimestampCal); - assert actualTimestamp >= timeBeforeSync : "Synchronization timestamp was not updated in shadow "+shadow; + assert actualTimestamp >= timeBeforeSync : "Synchronization timestamp was not updated in shadow " + shadow; // TODO: assert sync description } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractObjTemplateSyncTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractObjTemplateSyncTest.java index 3b4ecc9aab3..0ce064131c5 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractObjTemplateSyncTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractObjTemplateSyncTest.java @@ -50,9 +50,6 @@ public abstract class AbstractObjTemplateSyncTest extends AbstractInitializedMod protected static final File TASK_LIVE_SYNC_DUMMY_BYZANTINE_FILE = new File(TEST_DIR, "task-dummy-byzantine-livesync.xml"); protected static final String TASK_LIVE_SYNC_DUMMY_BYZANTINE_OID = "10000000-0000-0000-5555-55550000f904"; - protected static final File TASK_RECON_DUMMY_BYZANTINE_FILE = new File(TEST_DIR, "task-dummy-byzantine-recon.xml"); - protected static final String TASK_RECON_DUMMY_BYZANTINE_OID = "10000000-0000-0000-5656-56560000f904"; - protected static DummyResource dummyResourceByzantine; protected static DummyResourceContoller dummyResourceCtlByzantine; protected ResourceType resourceDummyByzantineType; @@ -107,31 +104,17 @@ protected int getWaitTimeout() { @Test public void test100ImportLiveSyncTaskDummyByzantine() throws Exception { - final String TEST_NAME = "test100ImportLiveSyncTaskDummyByzantine"; - - // GIVEN - AbstractObjTemplateSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); importSyncTask(resourceDummyByzantine); - // THEN then(); - waitForSyncTaskStart(resourceDummyByzantine); } // MID-2149 @Test public void test110AddDummyByzantineAccountMancomb() throws Exception { - final String TEST_NAME = "test110AddDummyByzantineAccountMancomb"; - // GIVEN - AbstractObjTemplateSyncTest.class.getName(); - Task task = getTestTask(); rememberTimeBeforeSync(); prepareNotifications(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractSynchronizationStoryTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractSynchronizationStoryTest.java index 3693fdd6e0d..ab794602987 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractSynchronizationStoryTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/AbstractSynchronizationStoryTest.java @@ -6,20 +6,15 @@ */ package com.evolveum.midpoint.model.intest.sync; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.FileNotFoundException; import java.net.ConnectException; import java.util.Collection; import java.util.Date; import java.util.List; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -47,19 +42,10 @@ import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; - -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractSynchronizationStoryTest extends AbstractInitializedModelIntegrationTest { @@ -78,7 +64,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); -// DebugUtil.setDetailedDebugDump(true); } @Override @@ -104,13 +89,6 @@ protected boolean isReconciliation() { @Test public void test100ImportLiveSyncTaskDummyGreen() throws Exception { - final String TEST_NAME = "test100ImportLiveSyncTaskDummyGreen"; - - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - /// WHEN when(); importSyncTask(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME)); @@ -123,12 +101,7 @@ public void test100ImportLiveSyncTaskDummyGreen() throws Exception { @Test public void test110AddDummyGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test110AddDummyGreenAccountMancomb"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -177,26 +150,12 @@ public void test110AddDummyGreenAccountMancomb() throws Exception { displayAllNotifications(); assertSingleDummyTransportMessageContaining("simpleAccountNotifier-SUCCESS", "Channel: " + getExpectedChannel()); notificationManager.setDisabled(true); -// checkDummyTransportMessages("userPasswordNotifier", 1); // password is generated by mapping (if there's none) -// checkDummyTransportMessages("accountPasswordNotifier", 1); // account password is then set -// checkDummyTransportMessages("simpleAccountNotifier-SUCCESS", 1); -// checkDummyTransportMessages("simpleAccountNotifier-FAILURE", 0); -// checkDummyTransportMessages("simpleAccountNotifier-ADD-SUCCESS", 0); // account itself is not added (only the shadow is!) -// checkDummyTransportMessages("simpleUserNotifier", 1); -// checkDummyTransportMessages("simpleUserNotifier-ADD", 1); } protected abstract String getExpectedChannel(); @Test public void test200ImportLiveSyncTaskDummyBlue() throws Exception { - final String TEST_NAME = "test200ImportLiveSyncTaskDummyBlue"; - - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - /// WHEN when(); importSyncTask(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); @@ -212,10 +171,7 @@ public void test200ImportLiveSyncTaskDummyBlue() throws Exception { */ @Test public void test210AddDummyGreenAccountWally() throws Exception { - final String TEST_NAME = "test210AddDummyGreenAccountWally"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); rememberTimeBeforeSync(); @@ -249,14 +205,6 @@ public void test210AddDummyGreenAccountWally() throws Exception { // notifications notificationManager.setDisabled(true); -// checkDummyTransportMessages("userPasswordNotifier", 1); // previously non-existing password is generated -// checkDummyTransportMessages("accountPasswordNotifier", 1); // password is then set on the account -// checkDummyTransportMessages("simpleAccountNotifier-SUCCESS", 2); // changes on green & blue (induced) -// checkDummyTransportMessages("simpleAccountNotifier-FAILURE", 0); -// checkDummyTransportMessages("simpleAccountNotifier-ADD-SUCCESS", 0); // account itself is not added (only the shadow is!) -// checkDummyTransportMessages("simpleUserNotifier", 1); -// checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - } /** @@ -264,10 +212,7 @@ public void test210AddDummyGreenAccountWally() throws Exception { */ @Test public void test220AddDummyBlueAccountWally() throws Exception { - final String TEST_NAME = "test220AddDummyBlueAccountWally"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); rememberTimeBeforeSync(); @@ -328,12 +273,7 @@ public void test220AddDummyBlueAccountWally() throws Exception { */ @Test public void test315AddDummyBlueAccountMancomb() throws Exception { - final String TEST_NAME = "test315AddDummyBlueAccountMancomb"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -385,13 +325,6 @@ public void test315AddDummyBlueAccountMancomb() throws Exception { */ @Test public void test350ImportLiveSyncTaskDummyDefault() throws Exception { - final String TEST_NAME = "test350ImportLiveSyncTaskDummyDefault"; - - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - /// WHEN when(); importSyncTask(getDummyResourceObject()); @@ -413,10 +346,7 @@ public void test350ImportLiveSyncTaskDummyDefault() throws Exception { */ @Test public void test360ModifyUserAddDummyDefaultAccount() throws Exception { - final String TEST_NAME = "test360ModifyUserAddDummyDefaultAccount"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); rememberTimeBeforeSync(); @@ -425,11 +355,11 @@ public void test360ModifyUserAddDummyDefaultAccount() throws Exception { assertEquals("OID of user wally have changed", userWallyOid, userWally.getOid()); ObjectDelta userDelta = createModifyUserAddAccount(userWally.getOid(), getDummyResourceObject()); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); /// WHEN when(); - modelService.executeChanges(deltas, null, task, result); + modelService.executeChanges(deltas, null, task, result); // THEN then(); @@ -447,11 +377,11 @@ public void test360ModifyUserAddDummyDefaultAccount() throws Exception { "default", "Wally Feed"); assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), - getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); - if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); + getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); + if (allwaysCheckTimestamp) { assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); } PrismObject accountWallyGreen = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME), getDummyResource(RESOURCE_DUMMY_GREEN_NAME), "green", "Wally Feed"); - if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); + if (allwaysCheckTimestamp) { assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); } userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); @@ -466,73 +396,13 @@ public void test360ModifyUserAddDummyDefaultAccount() throws Exception { assertUsers(8 + getNumberOfExtraDummyUsers()); } -// @Test -// public void test365ModifyDummyGreenAccountWallyUserTemplate() throws Exception { -// final String TEST_NAME = "test390ModifyDummyGreenAccountWallyUserTemplate"; -// displayTestTile(this, TEST_NAME); -// -// // GIVEN -// Task task = createTask(AbstractSynchronizationStoryTest.class.getName() + "." + TEST_NAME); -// OperationResult result = task.getResult(); -// rememberTimeBeforeSync(); -// -// addObjectFromFile(USER_TEMPLATE_SYNC_FILENAME, UserTemplateType.class, result); -// assumeUserTemplate(USER_TEMPLATE_SYNC_OID, getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME).asObjectable(), result); -// -// DummyAccount wallyDummyAccount = getDummyResource(RESOURCE_DUMMY_GREEN_NAME).getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); -// -// /// WHEN -// when(); -// wallyDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Wally Bloodnose"); -//// wallyDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "Cola"); -// -// // Wait for sync task to pick up the change -// waitForSyncTaskNextRun(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME)); -// -//// // Make sure that the "kickback" sync cycle of the other resource runs to completion -//// // We want to check the state after it gets stable -//// // and it could spoil the next test -// waitForSyncTaskNextRun(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); -// waitForSyncTaskNextRun(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME)); -//// // Make sure we have steady state -// waitForSyncTaskNextRun(resourceDummy); -// -// // THEN -// then(); -// -// PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); -// display("User wally", userWally); -// assertNotNull("User wally disappeared", userWally); -// assertUser(userWally, userWallyOid, ACCOUNT_WALLY_DUMMY_USERNAME, "Wally Bloodnose", null, "Wally Bloodnose from Sync"); -// -// PrismObject accountWallyGreen = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME), getDummyResource(RESOURCE_DUMMY_GREEN_NAME), "blue", "Wally Bloodnose"); -// if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); -// -//// PrismObject accountWallyGreen = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME), getDummyResource(RESOURCE_DUMMY_GREEN_NAME), "green", "Wally B. Feed"); -//// assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); -// PrismObject accountWallyDefault = checkWallyAccount(resourceDummy, dummyResource, "default", "Wally Bloodnose"); -// assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); -// -//// assertAccounts(userWally, 3); -// -//// assertLinked(userWally, accountWallyGreen); -// assertLinked(userWally, accountWallyGreen); -// assertLinked(userWally, accountWallyDefault); -// -// assertUsers(7 + getNumberOfExtraDummyUsers()); -// } - - /** * Change fullname on the green account. There is an inbound mapping to the user so it should propagate. * There is also outbound mapping from the user to dummy account, therefore it should propagate there as well. */ @Test public void test370ModifyDummyGreenAccountWally() throws Exception { - final String TEST_NAME = "test370ModifyDummyGreenAccountWally"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -573,7 +443,7 @@ public void test370ModifyDummyGreenAccountWally() throws Exception { PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); - if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); + if (allwaysCheckTimestamp) { assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); } PrismObject accountWallyGreen = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME), getDummyResource(RESOURCE_DUMMY_GREEN_NAME), "green", "Wally B. Feed"); assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); PrismObject accountWallyDefault; @@ -615,16 +485,13 @@ public void test370ModifyDummyGreenAccountWally() throws Exception { */ @Test public void test380ModifyUserWallyFullName() throws Exception { - final String TEST_NAME = "test380ModifyUserWallyFullName"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - DummyAccount wallyDummyAccount = getDummyResource(RESOURCE_DUMMY_GREEN_NAME).getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); + getDummyResource(RESOURCE_DUMMY_GREEN_NAME).getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); /// WHEN when(); @@ -656,7 +523,7 @@ public void test380ModifyUserWallyFullName() throws Exception { PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); - if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); + if (allwaysCheckTimestamp) { assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); } PrismObject accountWallyGreen = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME), getDummyResource(RESOURCE_DUMMY_GREEN_NAME), "green", "Bloodnose"); assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); @@ -664,7 +531,7 @@ public void test380ModifyUserWallyFullName() throws Exception { String fullNameDummyAttribute = IntegrationTestTools.getAttributeValue(accountWallyDefault.asObjectable(), new QName(ResourceTypeUtil.getResourceNamespace(getDummyResourceObject()), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME)); if (!"Bloodnose".equals(fullNameDummyAttribute) && !"Wally B. Feed".equals(fullNameDummyAttribute)) { - AssertJUnit.fail("Wrong full name on default dummy resource: "+fullNameDummyAttribute); + AssertJUnit.fail("Wrong full name on default dummy resource: " + fullNameDummyAttribute); } assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); @@ -685,16 +552,13 @@ public void test380ModifyUserWallyFullName() throws Exception { */ @Test public void test382ModifyUserWallyLocality() throws Exception { - final String TEST_NAME = "test382ModifyUserWallyLocality"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); - DummyAccount wallyDummyAccount = getDummyResource(RESOURCE_DUMMY_GREEN_NAME).getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); + getDummyResource(RESOURCE_DUMMY_GREEN_NAME).getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); /// WHEN when(); @@ -727,7 +591,7 @@ public void test382ModifyUserWallyLocality() throws Exception { PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); - if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); + if (allwaysCheckTimestamp) { assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); } PrismObject accountWallyGreen = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME), getDummyResource(RESOURCE_DUMMY_GREEN_NAME), "green", "Bloodnose"); assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); @@ -735,7 +599,7 @@ public void test382ModifyUserWallyLocality() throws Exception { String fullNameDummyAttribute = IntegrationTestTools.getAttributeValue(accountWallyDefault.asObjectable(), new QName(ResourceTypeUtil.getResourceNamespace(getDummyResourceObject()), DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME)); if (!"Bloodnose".equals(fullNameDummyAttribute) && !"Wally B. Feed".equals(fullNameDummyAttribute)) { - AssertJUnit.fail("Wrong full name on default dummy resource: "+fullNameDummyAttribute); + AssertJUnit.fail("Wrong full name on default dummy resource: " + fullNameDummyAttribute); } assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); assertShadowOperationalData(accountWallyDefault, SynchronizationSituationType.LINKED); @@ -758,7 +622,6 @@ public void test382ModifyUserWallyLocality() throws Exception { notificationManager.setDisabled(true); } - /** * Delete default dummy account. * Dummy resource has unlinkAccount sync reaction for deleted situation. The account should be unlinked @@ -766,10 +629,7 @@ public void test382ModifyUserWallyLocality() throws Exception { */ @Test public void test400DeleteDummyDefaultAccount() throws Exception { - final String TEST_NAME = "test400DeleteDummyDefaultAccount"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); rememberTimeBeforeSync(); @@ -779,10 +639,10 @@ public void test400DeleteDummyDefaultAccount() throws Exception { when(); getDummyResource().deleteAccountByName(ACCOUNT_WALLY_DUMMY_USERNAME); - display("Dummy (default) resource", getDummyResource().debugDump()); + display("Dummy (default) resource", getDummyResource().debugDump()); // Make sure we have steady state - waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); + waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME)); @@ -795,14 +655,14 @@ public void test400DeleteDummyDefaultAccount() throws Exception { assertNoDummyAccount(ACCOUNT_WALLY_DUMMY_USERNAME); assertShadow(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject()) - .assertTombstone() - .assertSynchronizationSituation(SynchronizationSituationType.DELETED); + .assertTombstone() + .assertSynchronizationSituation(SynchronizationSituationType.DELETED); PrismObject accountWallyBlue = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME), getDummyResource(RESOURCE_DUMMY_BLUE_NAME), "blue", "Wally Feed"); - if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); + if (allwaysCheckTimestamp) { assertShadowOperationalData(accountWallyBlue, SynchronizationSituationType.LINKED); } PrismObject accountWallyGreen = checkWallyAccount(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME), getDummyResource(RESOURCE_DUMMY_GREEN_NAME), "green", "Bloodnose"); - if (allwaysCheckTimestamp) assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); + if (allwaysCheckTimestamp) { assertShadowOperationalData(accountWallyGreen, SynchronizationSituationType.LINKED); } PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); @@ -835,20 +695,17 @@ public void test400DeleteDummyDefaultAccount() throws Exception { */ @Test public void test410DeleteDummyGreenAccount() throws Exception { - final String TEST_NAME = "test410DeleteDummyGreenAccount"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); prepareNotifications(); /// WHEN when(); - getDummyResource(RESOURCE_DUMMY_GREEN_NAME).deleteAccountByName(ACCOUNT_WALLY_DUMMY_USERNAME); + getDummyResource(RESOURCE_DUMMY_GREEN_NAME).deleteAccountByName(ACCOUNT_WALLY_DUMMY_USERNAME); - // Make sure we have steady state - waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); + // Make sure we have steady state + waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject()); OperationResult takResultBlue = waitForSyncTaskNextRun(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME)); waitForSyncTaskNextRunAssertSuccess(getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME)); @@ -861,13 +718,13 @@ public void test410DeleteDummyGreenAccount() throws Exception { assertNoDummyAccount(ACCOUNT_WALLY_DUMMY_USERNAME); assertShadow(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject()) - .assertTombstone() - .assertSynchronizationSituation(SynchronizationSituationType.DELETED); + .assertTombstone() + .assertSynchronizationSituation(SynchronizationSituationType.DELETED); assertNoDummyAccount(RESOURCE_DUMMY_GREEN_NAME, ACCOUNT_WALLY_DUMMY_USERNAME); assertShadow(ACCOUNT_WALLY_DUMMY_USERNAME, getDummyResourceObject(RESOURCE_DUMMY_GREEN_NAME)) - .assertTombstone() - .assertSynchronizationSituation(SynchronizationSituationType.DELETED); + .assertTombstone() + .assertSynchronizationSituation(SynchronizationSituationType.DELETED); PrismObject userWally = findUserByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); display("User wally", userWally); @@ -918,22 +775,11 @@ public void test410DeleteDummyGreenAccount() throws Exception { // notifications notificationManager.setDisabled(true); -// checkDummyTransportMessages("accountPasswordNotifier", 0); -// checkDummyTransportMessages("userPasswordNotifier", 0); -// checkDummyTransportMessages("simpleAccountNotifier-SUCCESS", 1); // default is already deleted, green is deleted manually -// checkDummyTransportMessages("simpleAccountNotifier-FAILURE", 0); -// checkDummyTransportMessages("simpleAccountNotifier-ADD-SUCCESS", 0); -// checkDummyTransportMessages("simpleUserNotifier", 1); -// checkDummyTransportMessages("simpleUserNotifier-ADD", 0); - } @Test public void test510AddDummyGreenAccountWallyUserTemplate() throws Exception { - final String TEST_NAME = "test510AddDummyGreenAccountWallyUserTemplate"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); rememberTimeBeforeSync(); @@ -962,11 +808,6 @@ public void test510AddDummyGreenAccountWallyUserTemplate() throws Exception { assertLinked(userWally, accountWallyGreen); assertUsers(8 + getNumberOfExtraDummyUsers()); - -// sync = ResourceTypeUtil.determineSynchronization(getDummyResourceObject(RESOURCE_DUMMY_BLUE_NAME).asObjectable(), UserType.class); -// if (sync != null){ -// sync.setObjectTemplateRef(null); -// } } /** @@ -974,12 +815,7 @@ public void test510AddDummyGreenAccountWallyUserTemplate() throws Exception { */ @Test public void test600AddDummyGreenAccountCalypso() throws Exception { - final String TEST_NAME = "test600AddDummyGreenAccountCalypso"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -1020,12 +856,7 @@ public void test600AddDummyGreenAccountCalypso() throws Exception { */ @Test public void test700AddDummyGreenAccountXjojo() throws Exception { - final String TEST_NAME = "test700AddDummyGreenAccountXjojo"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); @@ -1067,13 +898,6 @@ public void test700AddDummyGreenAccountXjojo() throws Exception { // notifications notificationManager.setDisabled(true); -// checkDummyTransportMessages("userPasswordNotifier", 1); // password is generated by mapping (if there's none) -// checkDummyTransportMessages("accountPasswordNotifier", 1); // account password is then set -// checkDummyTransportMessages("simpleAccountNotifier-SUCCESS", 1); -// checkDummyTransportMessages("simpleAccountNotifier-FAILURE", 0); -// checkDummyTransportMessages("simpleAccountNotifier-ADD-SUCCESS", 0); // account itself is not added (only the shadow is!) -// checkDummyTransportMessages("simpleUserNotifier", 1); -// checkDummyTransportMessages("simpleUserNotifier-ADD", 1); } private void assumeUserTemplate(String templateOid, ResourceType resource, String syncConfigName, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { @@ -1120,29 +944,29 @@ private PrismObject checkWallyAccount(PrismObject reso private PrismObject checkWallyAccount(PrismObject resource, DummyResource dummy, String resourceDesc, String expectedFullName, String shipName, String quote) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, ExpressionEvaluationException, InterruptedException { PrismObject accountShadowWally = findAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME, resource); - display("Account shadow wally ("+resourceDesc+")", accountShadowWally); - assertEquals("Wrong resourceRef in wally account ("+resourceDesc+")", resource.getOid(), + display("Account shadow wally (" + resourceDesc + ")", accountShadowWally); + assertEquals("Wrong resourceRef in wally account (" + resourceDesc + ")", resource.getOid(), accountShadowWally.asObjectable().getResourceRef().getOid()); if (expectedFullName != null) { - IntegrationTestTools.assertAttribute(accountShadowWally.asObjectable(), resource.asObjectable(), - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, expectedFullName); + IntegrationTestTools.assertAttribute(accountShadowWally.asObjectable(), resource.asObjectable(), + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, expectedFullName); } DummyAccount dummyAccount = dummy.getAccountByUsername(ACCOUNT_WALLY_DUMMY_USERNAME); - display("Account wally ("+resourceDesc+")", dummyAccount); - assertNotNull("No dummy account ("+resourceDesc+")", dummyAccount); + display("Account wally (" + resourceDesc + ")", dummyAccount); + assertNotNull("No dummy account (" + resourceDesc + ")", dummyAccount); if (expectedFullName != null) { - assertEquals("Wrong dummy account fullname ("+resourceDesc+")", expectedFullName, - dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME)); + assertEquals("Wrong dummy account fullname (" + resourceDesc + ")", expectedFullName, + dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME)); } - if (shipName != null){ - assertEquals("Wrong dummy account shipName ("+resourceDesc+")", shipName, + if (shipName != null) { + assertEquals("Wrong dummy account shipName (" + resourceDesc + ")", shipName, dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME)); } - if (quote != null){ - assertEquals("Wrong dummy account quote ("+resourceDesc+")", quote, + if (quote != null) { + assertEquals("Wrong dummy account quote (" + resourceDesc + ")", quote, dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME)); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTask.java index 43f832182c5..cb43a5fa995 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundLiveSyncTask.java @@ -6,7 +6,6 @@ */ package com.evolveum.midpoint.model.intest.sync; -import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.io.FileNotFoundException; @@ -59,12 +58,7 @@ protected String getSyncTaskOid(PrismObject resource) { @Override public void test199DeleteDummyEmeraldAccountMancomb() throws Exception { - final String TEST_NAME = "test199DeleteDummyEmeraldAccountMancomb"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTask.java index 6526d66f8b4..b2f7d15dc0a 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestInboundReconTask.java @@ -26,10 +26,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author semancik - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestInboundReconTask extends AbstractInboundSyncTest { @@ -64,12 +60,7 @@ protected String getSyncTaskOid(PrismObject resource) { @Override public void test180NoChange() throws Exception { - final String TEST_NAME = "test180NoChange"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); rememberTimeBeforeSync(); prepareNotifications(); @@ -107,12 +98,7 @@ public void test180NoChange() throws Exception { @Override public void test199DeleteDummyEmeraldAccountMancomb() throws Exception { - final String TEST_NAME = "test199DeleteDummyEmeraldAccountMancomb"; - // GIVEN - AbstractInboundSyncTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTask.java index 0420f24253a..15ec12b486d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTask.java @@ -77,15 +77,10 @@ protected String getSyncTaskOid(PrismObject resource) { @Test public void test999DeletingNotUpdatedShadowDummyGreen() throws Exception { - final String TEST_NAME = "test800DeletingNotUpdatedShadowDummyGreen"; String ACCOUNT_JACK_DUMMY_USERNAME = "jack"; String ACCOUNT_CAROL_DUMMY_USERNAME = "carol"; - // GIVEN - AbstractSynchronizationStoryTest.class.getName(); - Task task = getTestTask(); - OperationResult result = task.getResult(); rememberTimeBeforeSync(); prepareNotifications(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java index 4e49375c6c3..366e2804681 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestLiveSyncTaskMechanics.java @@ -148,7 +148,6 @@ private String getUserName(int i, boolean precise) { @Test public void test100SuspendWhileIcfSync() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -177,7 +176,6 @@ public void test100SuspendWhileIcfSync() throws Exception { @Test public void test105SuspendWhileIcfSyncImprecise() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -210,7 +208,6 @@ public void test105SuspendWhileIcfSyncImprecise() throws Exception { @Test public void test110SuspendWhileProcessing() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -264,7 +261,6 @@ public void test110SuspendWhileProcessing() throws Exception { @Test public void test115SuspendWhileProcessingImprecise() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -306,7 +302,6 @@ public void test115SuspendWhileProcessingImprecise() throws Exception { @Test public void test120Batched() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -372,7 +367,6 @@ public void test120Batched() throws Exception { @Test public void test125BatchedImprecise() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -417,7 +411,6 @@ public void test125BatchedImprecise() throws Exception { @Test public void test130Error() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -476,7 +469,6 @@ public void test130Error() throws Exception { @Test public void test135ErrorImprecise() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -541,7 +533,6 @@ public void test135ErrorImprecise() throws Exception { @Test public void test140DryRun() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -578,7 +569,6 @@ public void test140DryRun() throws Exception { @Test public void test150DryRunWithUpdate() throws Exception { // GIVEN - AbstractSynchronizationStoryTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java index 66f5831f87e..325e35d02c7 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java @@ -6,14 +6,9 @@ */ package com.evolveum.midpoint.model.intest.sync; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.File; -import java.util.Iterator; import java.util.List; import org.springframework.beans.factory.annotation.Autowired; @@ -32,7 +27,6 @@ import com.evolveum.midpoint.model.impl.util.DebugReconciliationTaskResultListener; import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.internals.InternalCounters; import com.evolveum.midpoint.schema.internals.InternalMonitor; import com.evolveum.midpoint.schema.internals.InternalOperationClasses; @@ -41,26 +35,13 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.asserter.UserAsserter; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUuid extends AbstractInitializedModelIntegrationTest { @@ -70,7 +51,6 @@ public class TestUuid extends AbstractInitializedModelIntegrationTest { protected static final File RESOURCE_DUMMY_UUID_FILE = new File(TEST_DIR, "resource-dummy-uuid.xml"); protected static final String RESOURCE_DUMMY_UUID_OID = "9792acb2-0b75-11e5-b66e-001e8c717e5b"; protected static final String RESOURCE_DUMMY_UUID_NAME = "uuid"; - protected static final String RESOURCE_DUMMY_UUID_NAMESPACE = MidPointConstants.NS_RI; protected static final File TASK_RECONCILE_DUMMY_UUID_FILE = new File(TEST_DIR, "task-reconcile-dummy-uuid.xml"); protected static final String TASK_RECONCILE_DUMMY_UUID_OID = "98ae26fc-0b76-11e5-b943-001e8c717e5b"; @@ -83,7 +63,6 @@ public class TestUuid extends AbstractInitializedModelIntegrationTest { private static final String ACCOUNT_AUGUSTINA_NAME = "augustina"; private static final String ACCOUNT_AUGUSTINA_FULLNAME = "Augustina LeWhat"; - protected DummyResource dummyResourceUuid; protected DummyResourceContoller dummyResourceCtlUuid; protected ResourceType resourceDummyUuidType; @@ -91,8 +70,7 @@ public class TestUuid extends AbstractInitializedModelIntegrationTest { private String augustusShadowOid; - - @Autowired(required=true) + @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; private DebugReconciliationTaskResultListener reconciliationTaskResultListener; @@ -117,13 +95,9 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // DebugUtil.setDetailedDebugDump(true); } - @Test public void test200ReconcileDummyUuid() throws Exception { - final String TEST_NAME = "test200ReconcileDummyUuid"; - // GIVEN - TestUuid.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); @@ -170,10 +144,7 @@ public void test200ReconcileDummyUuid() throws Exception { @Test public void test210ReconcileDummyUuidAddAugustus() throws Exception { - final String TEST_NAME = "test210ReconcileDummyUuidAddAugustus"; - // GIVEN - TestUuid.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); @@ -229,7 +200,7 @@ public void test210ReconcileDummyUuidAddAugustus() throws Exception { PrismObject user = findUserByUsername(USER_AUGUSTUS_NAME); display("Augustus after recon", user); augustusShadowOid = getSingleLinkOid(user); - PrismObject repoShadow = repositoryService.getObject(ShadowType.class, augustusShadowOid, null, result); + repositoryService.getObject(ShadowType.class, augustusShadowOid, null, result); } @@ -238,8 +209,6 @@ public void test210ReconcileDummyUuidAddAugustus() throws Exception { */ @Test public void test220ReconcileDummyUuidDeleteAddAugustus() throws Exception { - final String TEST_NAME = "test220ReconcileDummyUuidDeleteAddAugustus"; - // GIVEN TestUuid.class.getName(); Task task = getTestTask(); @@ -262,7 +231,7 @@ public void test220ReconcileDummyUuidDeleteAddAugustus() throws Exception { assertFalse("Account IDs not changed", oldAccount.getId().equals(newAccount.getId())); display("Old shadow OID", augustusShadowOid); - display("Account ID "+ oldAccount.getId() + " -> " + newAccount.getId()); + display("Account ID " + oldAccount.getId() + " -> " + newAccount.getId()); Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); @@ -308,18 +277,18 @@ public void test220ReconcileDummyUuidDeleteAddAugustus() throws Exception { TestUtil.assertSuccess(reconTaskResult); augustusShadowOid = assertUserAfterByUsername(USER_AUGUSTUS_NAME) - .links() + .links() .assertLinks(2) .by() - .dead(true) - .find() - .assertOid(augustusShadowOid) - .end() + .dead(true) + .find() + .assertOid(augustusShadowOid) + .end() .by() - .dead(false) - .find() - .assertOidDifferentThan(augustusShadowOid) - .getOid(); + .dead(false) + .find() + .assertOidDifferentThan(augustusShadowOid) + .getOid(); } /** @@ -328,10 +297,7 @@ public void test220ReconcileDummyUuidDeleteAddAugustus() throws Exception { */ @Test public void test230ReconcileDummyUuidDeleteAugustusAddAugustina() throws Exception { - final String TEST_NAME = "test230ReconcileDummyUuidDeleteAugustusAddAugustina"; - // GIVEN - TestUuid.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); @@ -350,7 +316,7 @@ public void test230ReconcileDummyUuidDeleteAugustusAddAugustina() throws Excepti assertFalse("Account IDs not changed", oldAccount.getId().equals(account.getId())); display("Old shadow OID", augustusShadowOid); - display("Account ID "+ oldAccount.getId() + " -> " + account.getId()); + display("Account ID " + oldAccount.getId() + " -> " + account.getId()); Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); @@ -396,16 +362,16 @@ public void test230ReconcileDummyUuidDeleteAugustusAddAugustina() throws Excepti TestUtil.assertSuccess(reconTaskResult); assertUserAfterByUsername(USER_AUGUSTUS_NAME) - .displayWithProjections() - .links() + .displayWithProjections() + .links() .assertLinks(3) .by() - .dead(true) - .assertCount(2) + .dead(true) + .assertCount(2) .by() - .dead(false) - .find() - .assertOidDifferentThan(augustusShadowOid); + .dead(false) + .find() + .assertOidDifferentThan(augustusShadowOid); } private void assertReconAuditModifications(int expectedModifications, String taskOid) { @@ -417,7 +383,7 @@ private void assertReconAuditModifications(int expectedModifications, String tas // Record from some other task, skip it auditRecords.removeIf(record -> record.getTaskOid() != null && !record.getTaskOid().equals(taskOid)); - int i=0; + int i = 0; while (i < (auditRecords.size() - 1)) { AuditEventRecord reconStartRecord = auditRecords.get(i); if (reconStartRecord.getEventType() == AuditEventType.EXECUTE_CHANGES_RAW) { @@ -425,35 +391,35 @@ private void assertReconAuditModifications(int expectedModifications, String tas continue; } assertNotNull("No reconStartRecord audit record", reconStartRecord); - assertEquals("Wrong stage in reconStartRecord audit record: "+reconStartRecord, AuditEventStage.REQUEST, reconStartRecord.getEventStage()); - assertEquals("Wrong type in reconStartRecord audit record: "+reconStartRecord, AuditEventType.RECONCILIATION, reconStartRecord.getEventType()); - assertTrue("Unexpected delta in reconStartRecord audit record "+reconStartRecord, reconStartRecord.getDeltas() == null || reconStartRecord.getDeltas().isEmpty()); + assertEquals("Wrong stage in reconStartRecord audit record: " + reconStartRecord, AuditEventStage.REQUEST, reconStartRecord.getEventStage()); + assertEquals("Wrong type in reconStartRecord audit record: " + reconStartRecord, AuditEventType.RECONCILIATION, reconStartRecord.getEventType()); + assertTrue("Unexpected delta in reconStartRecord audit record " + reconStartRecord, reconStartRecord.getDeltas() == null || reconStartRecord.getDeltas().isEmpty()); i++; break; } int modifications = 0; - for (; i < (auditRecords.size() - 1); i+=2) { + for (; i < (auditRecords.size() - 1); i += 2) { AuditEventRecord requestRecord = auditRecords.get(i); - assertNotNull("No request audit record ("+i+")", requestRecord); + assertNotNull("No request audit record (" + i + ")", requestRecord); if (requestRecord.getEventStage() == AuditEventStage.EXECUTION && requestRecord.getEventType() == AuditEventType.RECONCILIATION) { // end of audit records; break; } - assertEquals("Got this instead of request audit record ("+i+"): "+requestRecord, AuditEventStage.REQUEST, requestRecord.getEventStage()); + assertEquals("Got this instead of request audit record (" + i + "): " + requestRecord, AuditEventStage.REQUEST, requestRecord.getEventStage()); // Request audit may or may not have a delta. Usual records will not have a delta. But e.g. disableAccount reactions will have. - AuditEventRecord executionRecord = auditRecords.get(i+1); + AuditEventRecord executionRecord = auditRecords.get(i + 1); assertNotNull("No execution audit record (" + i + ")", executionRecord); assertEquals("Got this instead of execution audit record (" + i + "): " + executionRecord, AuditEventStage.EXECUTION, executionRecord.getEventStage()); - assertTrue("Empty deltas in execution audit record "+executionRecord, executionRecord.getDeltas() != null && ! executionRecord.getDeltas().isEmpty()); + assertTrue("Empty deltas in execution audit record " + executionRecord, executionRecord.getDeltas() != null && !executionRecord.getDeltas().isEmpty()); modifications++; - while (i+2 < auditRecords.size()) { - AuditEventRecord nextRecord = auditRecords.get(i+2); + while (i + 2 < auditRecords.size()) { + AuditEventRecord nextRecord = auditRecords.get(i + 2); if (nextRecord.getEventStage() == AuditEventStage.EXECUTION && nextRecord.getEventType() == requestRecord.getEventType()) { // this is an additional EXECUTION record due to changes in clockwork i++; @@ -466,46 +432,44 @@ private void assertReconAuditModifications(int expectedModifications, String tas AuditEventRecord reconStopRecord = auditRecords.get(i); assertNotNull("No reconStopRecord audit record", reconStopRecord); - assertEquals("Wrong stage in reconStopRecord audit record: "+reconStopRecord, AuditEventStage.EXECUTION, reconStopRecord.getEventStage()); - assertEquals("Wrong type in reconStopRecord audit record: "+reconStopRecord, AuditEventType.RECONCILIATION, reconStopRecord.getEventType()); - assertTrue("Unexpected delta in reconStopRecord audit record "+reconStopRecord, reconStopRecord.getDeltas() == null || reconStopRecord.getDeltas().isEmpty()); - } - - private void assertNoImporterUserByUsername(String username) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - PrismObject user = findUserByUsername(username); - assertNull("User "+username+" sneaked in", user); + assertEquals("Wrong stage in reconStopRecord audit record: " + reconStopRecord, AuditEventStage.EXECUTION, reconStopRecord.getEventStage()); + assertEquals("Wrong type in reconStopRecord audit record: " + reconStopRecord, AuditEventType.RECONCILIATION, reconStopRecord.getEventType()); + assertTrue("Unexpected delta in reconStopRecord audit record " + reconStopRecord, reconStopRecord.getDeltas() == null || reconStopRecord.getDeltas().isEmpty()); } private void assertImportedUserByOid(String userOid, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = getUser(userOid); - assertNotNull("No user "+userOid, user); + assertNotNull("No user " + userOid, user); assertImportedUser(user, resourceOids); } - private void assertImportedUserByUsername(String username, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private void assertImportedUserByUsername(String username, String... resourceOids) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(username); - assertNotNull("No user "+username, user); + assertNotNull("No user " + username, user); assertImportedUser(user, resourceOids); } - private void assertImportedUser(PrismObject user, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - UserAsserter userAsserter = assertUser(user,"imported") - .displayWithProjections() - .links() + private void assertImportedUser(PrismObject user, String... resourceOids) + throws ObjectNotFoundException, SchemaException { + UserAsserter userAsserter = assertUser(user, "imported") + .displayWithProjections() + .links() .by() - .dead(false) - .assertCount(resourceOids.length) + .dead(false) + .assertCount(resourceOids.length) .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); - for (String resourceOid: resourceOids) { + .assertAdministrativeStatus(ActivationStatusType.ENABLED); + for (String resourceOid : resourceOids) { userAsserter - .links() + .links() .by() - .resourceOid(resourceOid) - .dead(false) - .find() - .resolveTarget() - .assertKind(ShadowKindType.ACCOUNT); + .resourceOid(resourceOid) + .dead(false) + .find() + .resolveTarget() + .assertKind(ShadowKindType.ACCOUNT); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java index 2a56e031ceb..2fe18ec720d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java @@ -1412,10 +1412,7 @@ public void test190HermanGoesInvalid() throws Exception { @Test public void test200ImportTriggerScannerTask() throws Exception { - final String TEST_NAME = "test200ImportTriggerScannerTask"; - // GIVEN - TestTriggerTask.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1828,7 +1825,7 @@ public void test310HermanAssignJudgeBecomesValid() throws Exception { PrismObject user = getUser(USER_HERMAN_OID); display("User before", user); XMLGregorianCalendar start = (XMLGregorianCalendar) judgeAssignmentValidFrom.clone(); - start.add(XmlTypeConverter.createDuration(1*60*1000)); + start.add(XmlTypeConverter.createDuration(60 * 1000)); clock.override(start); display("Start", start); diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index 2f92537f920..52754d777c6 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -62,7 +62,6 @@ import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRule; import com.evolveum.midpoint.model.api.context.ModelContext; import com.evolveum.midpoint.model.api.context.ModelElementContext; -import com.evolveum.midpoint.model.api.context.ModelProjectionContext; import com.evolveum.midpoint.model.api.expr.MidpointFunctions; import com.evolveum.midpoint.model.api.hooks.HookRegistry; import com.evolveum.midpoint.model.api.interaction.DashboardService; @@ -120,6 +119,7 @@ import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.MidPointAsserts; import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.*; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.*; @@ -265,13 +265,15 @@ protected DummyResourceContoller initDummyResource(String name, File resourceFil return dummyResourceCollection.initDummyResource(name, resourceFile, resourceOid, null, task, result); } - protected DummyResourceContoller initDummyResourcePirate(String name, File resourceFile, String resourceOid, - Task task, OperationResult result) throws Exception { + protected DummyResourceContoller initDummyResourcePirate( + String name, File resourceFile, String resourceOid, Task task, OperationResult result) + throws Exception { return initDummyResource(name, resourceFile, resourceOid, controller -> controller.extendSchemaPirate(), task, result); } - protected DummyResourceContoller initDummyResourceAd(String name, File resourceFile, String resourceOid, - Task task, OperationResult result) throws Exception { + protected DummyResourceContoller initDummyResourceAd( + String name, File resourceFile, String resourceOid, Task task, OperationResult result) + throws Exception { return initDummyResource(name, resourceFile, resourceOid, controller -> controller.extendSchemaAd(), task, result); } @@ -283,11 +285,16 @@ protected DummyResourceContoller getDummyResourceController() { return getDummyResourceController(null); } - protected DummyAccountAsserter assertDummyAccountByUsername(String dummyResourceName, String username) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, InterruptedException { + protected DummyAccountAsserter assertDummyAccountByUsername( + String dummyResourceName, String username) + throws ConnectException, FileNotFoundException, SchemaViolationException, + ConflictException, InterruptedException { return getDummyResourceController(dummyResourceName).assertAccountByUsername(username); } - protected DummyGroupAsserter assertDummyGroupByName(String dummyResourceName, String name) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, InterruptedException { + protected DummyGroupAsserter assertDummyGroupByName(String dummyResourceName, String name) + throws ConnectException, FileNotFoundException, SchemaViolationException, + ConflictException, InterruptedException { return getDummyResourceController(dummyResourceName).assertGroupByName(name); } @@ -374,18 +381,30 @@ protected Throwable findCause(OperationResult result) { return null; } - protected PrismObject importAndGetObjectFromFile(Class type, String filename, String oid, Task task, OperationResult result) throws FileNotFoundException, ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject importAndGetObjectFromFile( + Class type, String filename, String oid, Task task, OperationResult result) + throws FileNotFoundException, ObjectNotFoundException, SchemaException, + SecurityViolationException, CommunicationException, ConfigurationException, + ExpressionEvaluationException { return importAndGetObjectFromFile(type, new File(filename), oid, task, result); } - protected PrismObject importAndGetObjectFromFile(Class type, File file, String oid, Task task, OperationResult result) throws FileNotFoundException, ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject importAndGetObjectFromFile( + Class type, File file, String oid, Task task, OperationResult result) + throws FileNotFoundException, ObjectNotFoundException, SchemaException, + SecurityViolationException, CommunicationException, ConfigurationException, + ExpressionEvaluationException { importObjectFromFile(file, result); OperationResult importResult = result.getLastSubresult(); TestUtil.assertSuccess("Import of " + file + " has failed", importResult); return modelService.getObject(type, oid, null, task, result); } - protected PrismObject importAndGetObjectFromFileIgnoreWarnings(Class type, File file, String oid, Task task, OperationResult result) throws FileNotFoundException, ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject importAndGetObjectFromFileIgnoreWarnings( + Class type, File file, String oid, Task task, OperationResult result) + throws FileNotFoundException, ObjectNotFoundException, SchemaException, + SecurityViolationException, CommunicationException, ConfigurationException, + ExpressionEvaluationException { importObjectFromFile(file, result); OperationResult importResult = result.getLastSubresult(); OperationResultStatus status = importResult.getStatus(); @@ -408,22 +427,28 @@ protected void assertUsers(int expectedNumberOfUsers) assertObjects(UserType.class, expectedNumberOfUsers); } - protected void assertRoles(int expectedNumberOfUsers) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertRoles(int expectedNumberOfUsers) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { assertObjects(RoleType.class, expectedNumberOfUsers); } - protected void assertServices(int expectedNumberOfUsers) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertServices(int expectedNumberOfUsers) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { assertObjects(ServiceType.class, expectedNumberOfUsers); } - protected void assertObjects(Class type, int expectedNumberOfUsers) throws SchemaException, - ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertObjects(Class type, int expectedNumberOfUsers) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { assertObjects(type, null, expectedNumberOfUsers); } - protected void assertObjects(Class type, ObjectQuery query, int expectedNumberOfUsers) - throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, - ConfigurationException, ExpressionEvaluationException { + protected void assertObjects( + Class type, ObjectQuery query, int expectedNumberOfUsers) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { assertEquals("Unexpected number of " + type.getSimpleName() + "s", expectedNumberOfUsers, getObjectCount(type, query)); } @@ -1727,19 +1752,28 @@ protected Collection> listAccounts( return modelService.searchObjects(ShadowType.class, query, null, task, result); } - protected PrismObject getShadowModel(String accountOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject getShadowModel(String accountOid) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { return getShadowModel(accountOid, null, true); } - protected PrismObject getShadowModelNoFetch(String accountOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject getShadowModelNoFetch(String accountOid) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { return getShadowModel(accountOid, GetOperationOptions.createNoFetch(), true); } - protected PrismObject getShadowModelFuture(String accountOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject getShadowModelFuture(String accountOid) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { return getShadowModel(accountOid, GetOperationOptions.createPointInTimeType(PointInTimeType.FUTURE), true); } - protected PrismObject getShadowModel(String shadowOid, GetOperationOptions rootOptions, boolean assertSuccess) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected PrismObject getShadowModel( + String shadowOid, GetOperationOptions rootOptions, boolean assertSuccess) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = createPlainTask("getShadowModel"); OperationResult result = task.getResult(); Collection> opts = null; @@ -1845,7 +1879,8 @@ protected PrismObject findShadowByNameViaModel(ShadowKindType kind, return shadows.iterator().next(); } - protected ObjectQuery createAccountShadowQuery(String username, PrismObject resource) throws SchemaException { + protected ObjectQuery createAccountShadowQuery( + String username, PrismObject resource) throws SchemaException { RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); RefinedObjectClassDefinition rAccount = rSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); Collection identifierDefs = rAccount.getPrimaryIdentifiers(); @@ -2087,23 +2122,29 @@ protected static void assertAssignedOrgs(PrismObject us MidPointAsserts.assertAssignedOrgs(user, orgOids); } - protected void assertObjectRefs(String contextDesc, Collection real, ObjectType... expected) { + @UnusedTestElement + protected void assertObjectRefs(String contextDesc, Collection real, ObjectType... expected) { assertObjectRefs(contextDesc, real, objectsToOids(expected)); } - protected void assertPrismRefValues(String contextDesc, Collection real, ObjectType... expected) { + @UnusedTestElement + protected void assertPrismRefValues( + String contextDesc, Collection real, ObjectType... expected) { assertPrismRefValues(contextDesc, real, objectsToOids(expected)); } - protected void assertPrismRefValues(String contextDesc, Collection real, Collection expected) { + protected void assertPrismRefValues(String contextDesc, + Collection real, Collection expected) { assertPrismRefValues(contextDesc, real, objectsToOids(expected)); } - protected void assertObjectRefs(String contextDesc, Collection real, String... expected) { + protected void assertObjectRefs( + String contextDesc, Collection real, String... expected) { assertObjectRefs(contextDesc, true, real, expected); } - protected void assertObjectRefs(String contextDesc, boolean checkNames, Collection real, String... expected) { + protected void assertObjectRefs(String contextDesc, + boolean checkNames, Collection real, String... expected) { List refOids = new ArrayList<>(); for (ObjectReferenceType ref : real) { refOids.add(ref.getOid()); @@ -2147,21 +2188,19 @@ protected void assertDelegatedRef(PrismObject focus, St } protected void assertNotAssignedRole( - PrismObject focus, String roleOid, Task task, OperationResult result) { + PrismObject focus, String roleOid, OperationResult result) { MidPointAsserts.assertNotAssignedRole(focus, roleOid); } - protected void assertNotAssignedRole(String userOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertNotAssignedRole(String userOid, String roleOid, OperationResult result) + throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); MidPointAsserts.assertNotAssignedRole(user, roleOid); } - protected void assertNotAssignedResource(String userOid, String resourceOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { - PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); - MidPointAsserts.assertNotAssignedResource(user, resourceOid); - } - - protected void assertAssignedResource(Class type, String userOid, String resourceOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertAssignedResource( + Class type, String userOid, String resourceOid, OperationResult result) + throws ObjectNotFoundException, SchemaException { PrismObject focus = repositoryService.getObject(type, userOid, null, result); MidPointAsserts.assertAssignedResource(focus, resourceOid); } @@ -2174,7 +2213,9 @@ protected void assertNotAssignedOrg(PrismObject user, S MidPointAsserts.assertNotAssignedOrg(user, orgOid, relation); } - protected void assertAssignedOrg(String userOid, String orgOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertAssignedOrg( + String userOid, String orgOid, OperationResult result) + throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedOrg(user, orgOid); } @@ -2195,7 +2236,8 @@ protected AssignmentType assertAssignedOrg(PrismObject user, PrismObje return MidPointAsserts.assertAssignedOrg(user, org.getOid()); } - protected void assertHasOrg(String userOid, String orgOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { + protected void assertHasOrg(String userOid, String orgOid, OperationResult result) + throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedOrg(user, orgOid); } @@ -2231,6 +2273,7 @@ protected void assertHasOrgs(PrismObject user, int exp MidPointAsserts.assertHasOrgs(user, expectedNumber); } + @UnusedTestElement protected void assertHasArchetypes(PrismObject object, String... oids) { for (String oid : oids) { assertHasArchetype(object, oid); @@ -2305,14 +2348,17 @@ private void dumpSubOrgs(StringBuilder sb, String baseOrgOid, boolean dumpUsers, for (PrismObject suborg : subOrgs) { dumpOrg(sb, suborg, indent); if (dumpUsers) { - dumpOrgUsers(sb, suborg.getOid(), dumpUsers, indent + 1, task, result); + dumpOrgUsers(sb, suborg.getOid(), indent + 1, task, result); } sb.append("\n"); dumpSubOrgs(sb, suborg.getOid(), dumpUsers, indent + 1, task, result); } } - private void dumpOrgUsers(StringBuilder sb, String baseOrgOid, boolean dumpUsers, int indent, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private void dumpOrgUsers( + StringBuilder sb, String baseOrgOid, int indent, Task task, OperationResult result) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { List> subUsers = getSubOrgUsers(baseOrgOid, task, result); for (PrismObject subuser : subUsers) { sb.append("\n"); @@ -2415,21 +2461,11 @@ protected void assertAssigned(PrismObject us MidPointAsserts.assertAssigned(user, targetOid, refType); } - protected void assertAssignedNoOrg(String userOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException { - PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); - assertAssignedNoOrg(user); - } - protected void assertAssignedNoOrg(PrismObject user) { assertAssignedNo(user, OrgType.COMPLEX_TYPE); } - protected void assertAssignedNoRole( - PrismObject focus, Task task, OperationResult result) { - assertAssignedNoRole(focus); - } - - protected void assertAssignedNoRole(String userOid, Task task, OperationResult result) + protected void assertAssignedNoRole(String userOid, OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedNoRole(user); @@ -2452,7 +2488,7 @@ protected void assertAssignedNo(PrismObject user, QName } protected void assertAssignedAccount( - String userOid, String resourceOid, Task task, OperationResult result) + String userOid, String resourceOid, OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertAssignedAccount(user, resourceOid); @@ -2564,11 +2600,6 @@ protected PrismObject createUser(String name, String givenName, String return user; } - protected void fillinUser(PrismObject user, String name, String fullName) { - user.asObjectable().setName(createPolyStringType(name)); - user.asObjectable().setFullName(createPolyStringType(fullName)); - } - protected void fillinUserAssignmentAccountConstruction(PrismObject user, String resourceOid) { AssignmentType assignmentType = new AssignmentType(); ConstructionType accountConstruntion = new ConstructionType(); @@ -2751,7 +2782,8 @@ protected void setGlobalSecurityPolicy(String securityPolicyOid, OperationResult } - protected void modifySystemObjectInRepo(Class type, String oid, Collection modifications, OperationResult parentResult) + protected void modifySystemObjectInRepo(Class type, String oid, + Collection modifications, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { display("Modifications of system object " + oid, modifications); repositoryService.modifyObject(type, oid, modifications, parentResult); @@ -2770,15 +2802,6 @@ protected ItemPath getIcfsNameAttributePath() { } - protected void assertResolvedResourceRefs(ModelContext context) { - for (ModelProjectionContext projectionContext : context.getProjectionContexts()) { - assertResolvedResourceRefs(projectionContext.getObjectOld(), "objectOld in " + projectionContext); - assertResolvedResourceRefs(projectionContext.getObjectNew(), "objectNew in " + projectionContext); - assertResolvedResourceRefs(projectionContext.getPrimaryDelta(), "primaryDelta in " + projectionContext); - assertResolvedResourceRefs(projectionContext.getSecondaryDelta(), "secondaryDelta in " + projectionContext); - } - } - private void assertResolvedResourceRefs(ObjectDelta delta, String desc) { if (delta == null) { return; @@ -2918,7 +2941,7 @@ protected ObjectDelta createModifyUserAddAccount(String userOid, Prism resourceRef.setOid(resource.getOid()); account.asObjectable().setResourceRef(resourceRef); RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); - RefinedObjectClassDefinition rocd = null; + RefinedObjectClassDefinition rocd; if (StringUtils.isNotBlank(intent)) { rocd = refinedSchema.getRefinedDefinition(ShadowKindType.ACCOUNT, intent); account.asObjectable().setIntent(intent); @@ -3006,9 +3029,7 @@ public boolean check() throws CommonException { public void timeout() { try { task.refresh(waitResult); - } catch (ObjectNotFoundException e) { - logger.error("Exception during task refresh: {}", e, e); - } catch (SchemaException e) { + } catch (ObjectNotFoundException | SchemaException e) { logger.error("Exception during task refresh: {}", e, e); } OperationResult result = task.getResult(); @@ -3027,7 +3048,8 @@ protected void waitForTaskCloseOrSuspend(String taskOid, final int timeout) thro waitForTaskCloseOrSuspend(taskOid, timeout, DEFAULT_TASK_SLEEP_TIME); } - protected void waitForTaskCloseOrSuspend(final String taskOid, final int timeout, long sleepTime) throws Exception { + protected void waitForTaskCloseOrSuspend( + final String taskOid, final int timeout, long sleepTime) throws Exception { final OperationResult waitResult = new OperationResult(AbstractIntegrationTest.class + ".waitForTaskCloseOrSuspend"); Checker checker = new Checker() { @Override @@ -3649,18 +3671,6 @@ protected void assertTaskExecutionStatus(String taskOid, TaskExecutionStatus exp assertEquals("Wrong executionStatus in " + task, expectedExecutionStatus, task.getExecutionStatus()); } - protected void setSecurityContextUser(String userOid) - throws ObjectNotFoundException, SchemaException, SecurityViolationException, - CommunicationException, ConfigurationException, ExpressionEvaluationException { - Task task = createPlainTask("setSecurityContextUser"); - PrismObject object = modelService.getObject(UserType.class, userOid, null, task, task.getResult()); - - assertNotNull("User " + userOid + " is null", object.asObjectable()); - SecurityContextHolder.getContext().setAuthentication( - new UsernamePasswordAuthenticationToken( - new MidPointPrincipal(object.asObjectable()), null)); - } - protected String getSecurityContextUserOid() { return ((MidPointPrincipal) (SecurityContextHolder.getContext().getAuthentication().getPrincipal())).getOid(); } @@ -3749,11 +3759,15 @@ protected void assertEffectualDeltas(ObjectDelta focusD } private boolean isSideEffectDelta(ItemDelta modification) { - if (modification.getPath().containsNameExactly(ObjectType.F_METADATA) || - (modification.getPath().containsNameExactly(FocusType.F_ASSIGNMENT) && modification.getPath().containsNameExactly(ActivationType.F_EFFECTIVE_STATUS))) { + if (modification.getPath().containsNameExactly(ObjectType.F_METADATA) + || (modification.getPath().containsNameExactly(FocusType.F_ASSIGNMENT) + && modification.getPath().containsNameExactly(ActivationType.F_EFFECTIVE_STATUS))) { return true; - } else if (modification.getPath().containsNameExactly(FocusType.F_ASSIGNMENT) && modification.getPath().containsNameExactly(AssignmentType.F_ACTIVATION) && modification.isReplace() && (modification instanceof ContainerDelta)) { - Collection> valuesToReplace = ((ContainerDelta) modification).getValuesToReplace(); + } else if (modification.getPath().containsNameExactly(FocusType.F_ASSIGNMENT) + && modification.getPath().containsNameExactly(AssignmentType.F_ACTIVATION) + && modification.isReplace() && (modification instanceof ContainerDelta)) { + Collection> valuesToReplace = + ((ContainerDelta) modification).getValuesToReplace(); if (valuesToReplace != null && valuesToReplace.size() == 1) { PrismContainerValue cval = valuesToReplace.iterator().next(); if (cval.size() == 1) { @@ -3857,7 +3871,10 @@ protected PrismObject getObjectViaRepo(Class type, return object; } - protected void addObjects(File... files) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException, IOException { + protected void addObjects(File... files) + throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException, IOException { for (File file : files) { addObject(file); } @@ -3924,12 +3941,20 @@ protected String addObject(PrismObject object, ModelEx return object.getOid(); } - protected void deleteObject(Class type, String oid, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + protected void deleteObject( + Class type, String oid, Task task, OperationResult result) + throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException { ObjectDelta delta = prismContext.deltaFactory().object().createDeleteDelta(type, oid); executeChanges(delta, null, task, result); } - protected void deleteObjectRaw(Class type, String oid, Task task, OperationResult result) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + protected void deleteObjectRaw( + Class type, String oid, Task task, OperationResult result) + throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException { ObjectDelta delta = prismContext.deltaFactory().object().createDeleteDelta(type, oid); executeChanges(delta, ModelExecuteOptions.createRaw(), task, result); } @@ -3953,7 +3978,7 @@ protected void deleteObjectRepo(Class type, String oid TestUtil.assertSuccess(result); } - protected void forceDeleteShadow(String oid) + protected void forceDeleteShadow(String oid) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java index 42403a0e2ec..407f63dc4c7 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java @@ -168,7 +168,7 @@ public void test020DeleteRole1Assignment() throws Exception { assertEquals("Wrong context state", ModelState.FINAL, context.getState()); result.computeStatusIfUnknown(); TestUtil.assertSuccess(result); - assertNotAssignedRole(getUser(userJackOid), getRoleOid(1), task, result); + assertNotAssignedRole(getUser(userJackOid), getRoleOid(1), result); } /** @@ -388,7 +388,7 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati checkAuditRecords(createResultMap(getRoleOid(1), WorkflowResult.APPROVED)); checkUserApprovers(userJackOid, Collections.singletonList(realApproverOid), result); } else { - assertNotAssignedRole(userJackOid, getRoleOid(1), opTask, result); + assertNotAssignedRole(userJackOid, getRoleOid(1), result); } } } @@ -534,7 +534,7 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati } else { assertUserNoProperty(userJackOid, UserType.F_DESCRIPTION); } - assertNotAssignedRole(userJackOid, getRoleOid(4), opTask, result); + assertNotAssignedRole(userJackOid, getRoleOid(4), result); } break; case 1: @@ -543,7 +543,7 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati if (yes) { assertAssignedRole(userJackOid, getRoleOid(number), result); } else { - assertNotAssignedRole(userJackOid, getRoleOid(number), opTask, result); + assertNotAssignedRole(userJackOid, getRoleOid(number), result); } break; diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java index adeded9a887..7e1a7842108 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java @@ -1176,7 +1176,7 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati if (yes) { assertAssignedRole(userJackOid, oids[number-1], result); } else { - assertNotAssignedRole(userJackOid, oids[number-1], opTask, result); + assertNotAssignedRole(userJackOid, oids[number-1], result); } break; @@ -1442,8 +1442,8 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati } } if (yes || !has1and2) { - assertNotAssignedRole(userJackOid, roleRole21Oid, opTask, result); - assertNotAssignedRole(userJackOid, roleRole22Oid, opTask, result); + assertNotAssignedRole(userJackOid, roleRole21Oid, result); + assertNotAssignedRole(userJackOid, roleRole22Oid, result); } else { assertAssignedRole(userJackOid, roleRole21Oid, result); assertAssignedRole(userJackOid, roleRole22Oid, result); @@ -1451,7 +1451,7 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati break; case 1: if (yes) { - assertNotAssignedRole(userJackOid, roleRole23Oid, opTask, result); + assertNotAssignedRole(userJackOid, roleRole23Oid, result); } else { assertAssignedRole(userJackOid, roleRole23Oid, result); } diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestDelegation.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestDelegation.java index aec8874cfa1..373112f34d3 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestDelegation.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestDelegation.java @@ -79,7 +79,7 @@ public void test100CreateTask() throws Exception { OperationResult result = getTestOperationResult(); assignRole(userJackOid, ROLE_PRINCE_OID, task, result); // should start approval process - assertNotAssignedRole(userJackOid, ROLE_PRINCE_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_PRINCE_OID, result); CaseWorkItemType workItem = getWorkItem(task, result); workItemId = WorkItemId.of(workItem); diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEscalation.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEscalation.java index 1e2a876d6c5..50a8aab4781 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEscalation.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEscalation.java @@ -93,7 +93,7 @@ public void test100CreateE1ApprovalCase() throws Exception { OperationResult result = getTestOperationResult(); assignRole(userJackOid, ROLE_E1_OID, task, result); // should start approval process - assertNotAssignedRole(userJackOid, ROLE_E1_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_E1_OID, result); CaseWorkItemType workItem = getWorkItem(task, result); WorkItemId.of(workItem); @@ -193,7 +193,7 @@ public void test200CreateE2ApprovalCase() throws Exception { assignRole(userJackOid, ROLE_E2_OID, task, result); // should start approval process // THEN - assertNotAssignedRole(userJackOid, ROLE_E2_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_E2_OID, result); List workItems = getWorkItems(task, result); displayWorkItems("Work items", workItems); diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEvents.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEvents.java index 2e37b68a388..7ce2150b6dd 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEvents.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestEvents.java @@ -61,7 +61,7 @@ public void test100CreateTask() throws Exception { OperationResult result = getTestOperationResult(); assignRole(userJackOid, roleNoApproversOid, task, result); // should start approval process - assertNotAssignedRole(userJackOid, roleNoApproversOid, task, result); + assertNotAssignedRole(userJackOid, roleNoApproversOid, result); CaseWorkItemType workItem = getWorkItem(task, result); workItemId = WorkItemId.of(workItem); diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestMiscellaneous.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestMiscellaneous.java index 97abbe1e517..a21d2a9b03c 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestMiscellaneous.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestMiscellaneous.java @@ -117,7 +117,7 @@ public void test100RequesterComment() throws Exception { Collection> deltas = MiscSchemaUtil.createCollection(userDelta); modelService.executeChanges(deltas, ModelExecuteOptions.createRequestBusinessContext(businessContext), task, result); - assertNotAssignedRole(userJackOid, ROLE_SAILOR_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_SAILOR_OID, result); CaseWorkItemType workItem = getWorkItem(task, result); display("Work item", workItem); @@ -184,7 +184,7 @@ public void test105RequesterCommentImmediate() throws Exception { options.setExecuteImmediatelyAfterApproval(true); modelService.executeChanges(deltas, options, task, result); - assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, result); CaseWorkItemType workItem = getWorkItem(task, result); display("Work item", workItem); @@ -252,7 +252,7 @@ public void test110RequestPrunedRole() throws Exception { result.computeStatus(); TestUtil.assertInProgress("Operation NOT in progress", result); - assertNotAssignedRole(userJackOid, ROLE_SILVER_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_SILVER_OID, result); // complete the work item related to assigning role silver CaseWorkItemType workItem = getWorkItem(task, result); @@ -265,7 +265,7 @@ public void test110RequestPrunedRole() throws Exception { CaseType rootCase = getCase(aCase.getParentRef().getOid()); waitForCaseClose(rootCase); - assertNotAssignedRole(userJackOid, ROLE_GOLD_OID, task, result); // should be pruned without approval + assertNotAssignedRole(userJackOid, ROLE_GOLD_OID, result); // should be pruned without approval } @Test @@ -278,7 +278,7 @@ public void test200GetRoleByTemplate() throws Exception { // GIVEN setDefaultUserTemplate(TEMPLATE_ASSIGNING_CAPTAIN_OID); unassignAllRoles(userJackOid); - assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, result); // WHEN // some innocent change @@ -301,7 +301,7 @@ public void test210GetRoleByTemplateAfterAssignments() throws Exception { // GIVEN setDefaultUserTemplate(TEMPLATE_ASSIGNING_CAPTAIN_AFTER_OID); unassignAllRoles(userJackOid); - assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, result); // WHEN // some innocent change @@ -325,7 +325,7 @@ public void test220GetRoleByFocusMappings() throws Exception { // GIVEN setDefaultUserTemplate(null); unassignAllRoles(userJackOid); - assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, result); // WHEN assignRole(userJackOid, ROLE_ASSIGNING_CAPTAIN_OID, task, result); @@ -347,7 +347,7 @@ public void test250SkippingApprovals() throws Exception { // GIVEN setDefaultUserTemplate(null); unassignAllRoles(userJackOid); - assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, task, result); + assertNotAssignedRole(userJackOid, ROLE_CAPTAIN_OID, result); // WHEN ObjectDelta delta = diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestParallelApprovals.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestParallelApprovals.java index 9ae8b938a53..e69fc4ddd9d 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestParallelApprovals.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestParallelApprovals.java @@ -130,9 +130,9 @@ public void test100ParallelApprovals() throws Exception { ObjectTypeUtil.createAssignmentTo(roleRole53aOid, ObjectTypes.ROLE, prismContext)) .asObjectDeltaCast(userJackOid); executeChanges(assignDelta, createExecuteImmediatelyAfterApproval(), task, result); // should start approval processes - assertNotAssignedRole(userJackOid, roleRole51aOid, task, result); - assertNotAssignedRole(userJackOid, roleRole52aOid, task, result); - assertNotAssignedRole(userJackOid, roleRole53aOid, task, result); + assertNotAssignedRole(userJackOid, roleRole51aOid, result); + assertNotAssignedRole(userJackOid, roleRole52aOid, result); + assertNotAssignedRole(userJackOid, roleRole53aOid, result); display("Task after operation", task); @@ -248,9 +248,9 @@ public void test120ParallelApprovalsInTwoOperations() throws Exception { ObjectTypeUtil.createAssignmentTo(roleRole53aOid, ObjectTypes.ROLE, prismContext)) .asObjectDeltaCast(userBobOid); executeChanges(assignDelta2, createExecuteImmediatelyAfterApproval(), task2, result2); // should start approval processes - assertNotAssignedRole(userBobOid, roleRole51aOid, task0, result0); - assertNotAssignedRole(userBobOid, roleRole52aOid, task0, result0); - assertNotAssignedRole(userBobOid, roleRole53aOid, task0, result0); + assertNotAssignedRole(userBobOid, roleRole51aOid, result0); + assertNotAssignedRole(userBobOid, roleRole52aOid, result0); + assertNotAssignedRole(userBobOid, roleRole53aOid, result0); display("Task1 after operation", task1); display("Task2 after operation", task2); @@ -305,9 +305,9 @@ public void test130ParallelApprovalsInThreeSummarizingOperations() throws Except assignRole(userChuckOid, roleRole51aOid, task1, result1); assignRole(userChuckOid, roleRole52aOid, task2, result2); assignRole(userChuckOid, roleRole53aOid, task3, result3); - assertNotAssignedRole(userChuckOid, roleRole51aOid, task0, result0); - assertNotAssignedRole(userChuckOid, roleRole52aOid, task0, result0); - assertNotAssignedRole(userChuckOid, roleRole53aOid, task0, result0); + assertNotAssignedRole(userChuckOid, roleRole51aOid, result0); + assertNotAssignedRole(userChuckOid, roleRole52aOid, result0); + assertNotAssignedRole(userChuckOid, roleRole53aOid, result0); display("Task1 after operation", task1); display("Task2 after operation", task2); diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestSoD.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestSoD.java index 36f5c215b22..6c70e63a6c2 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestSoD.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/other/TestSoD.java @@ -185,7 +185,7 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati if (yes) { assertAssignedRole(userJackOid, rolePirateOid, result); } else { - assertNotAssignedRole(userJackOid, rolePirateOid, opTask, result); + assertNotAssignedRole(userJackOid, rolePirateOid, result); } break; } @@ -217,7 +217,7 @@ public void test030AssignRoleRespectable() throws Exception { // GIVEN unassignRole(userJackOid, rolePirateOid, task, result); - assertNotAssignedRole(userJackOid, rolePirateOid, task, result); + assertNotAssignedRole(userJackOid, rolePirateOid, result); // WHEN+THEN PrismObject jack = getUser(userJackOid); @@ -286,7 +286,7 @@ protected void assertDeltaExecuted(int number, boolean yes, Task opTask, Operati if (yes) { assertAssignedRole(userJackOid, roleRespectableOid, result); } else { - assertNotAssignedRole(userJackOid, roleRespectableOid, opTask, result); + assertNotAssignedRole(userJackOid, roleRespectableOid, result); } break; } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java index b1e06c992aa..58be22ba044 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractDummyTest.java @@ -414,7 +414,6 @@ protected void checkRepoAccountShadow(PrismObject shadowFromRepo) { protected void assertDummyConnectorInstances(int expectedConnectorInstances) throws NumberFormatException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - AbstractDummyTest.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); List stats = provisioningService.getConnectorOperationalStatus(RESOURCE_DUMMY_OID, task, result); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuidNonUniqueName.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuidNonUniqueName.java index e3dc5771c71..7f5892bd31c 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuidNonUniqueName.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyUuidNonUniqueName.java @@ -111,7 +111,7 @@ public void test600AddAccountAlreadyExist() { // DO nothing. This test is meaningless in non-unique environment } - private String addFettucini(File file, String oid, String expectedFullName) throws Exception { + private void addFettucini(File file, String oid, String expectedFullName) throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -169,11 +169,9 @@ private String addFettucini(File file, String oid, String expectedFullName) thro checkUniqueness(accountProvisioning); assertSteadyResource(); - return icfUid; } private void searchFettucini(int expectedNumberOfFettucinis) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - TestDummy.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = prismContext.queryFor(ShadowType.class) diff --git a/repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/expression/ExpressionUtil.java b/repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/expression/ExpressionUtil.java index d5317838738..66e9dac40d1 100644 --- a/repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/expression/ExpressionUtil.java +++ b/repo/repo-common/src/main/java/com/evolveum/midpoint/repo/common/expression/ExpressionUtil.java @@ -11,37 +11,13 @@ import java.util.Collections; import java.util.List; import java.util.function.Function; - import javax.xml.namespace.QName; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; -import com.evolveum.midpoint.prism.ComplexTypeDefinition; -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.MutablePrismPropertyDefinition; -import com.evolveum.midpoint.prism.Objectable; -import com.evolveum.midpoint.prism.PrimitiveType; -import com.evolveum.midpoint.prism.PrismContainer; -import com.evolveum.midpoint.prism.PrismContainerDefinition; -import com.evolveum.midpoint.prism.PrismContainerValue; -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.PrismReferenceDefinition; -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.PrismValueCollectionsUtil; -import com.evolveum.midpoint.prism.Referencable; -import com.evolveum.midpoint.prism.Structured; import com.evolveum.midpoint.prism.Visitor; +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.ItemDelta; @@ -49,19 +25,7 @@ import com.evolveum.midpoint.prism.delta.PrismValueDeltaSetTriple; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.query.AllFilter; -import com.evolveum.midpoint.prism.query.ExistsFilter; -import com.evolveum.midpoint.prism.query.FilterCreationUtil; -import com.evolveum.midpoint.prism.query.FullTextFilter; -import com.evolveum.midpoint.prism.query.InOidFilter; -import com.evolveum.midpoint.prism.query.LogicalFilter; -import com.evolveum.midpoint.prism.query.NoneFilter; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.prism.query.OrgFilter; -import com.evolveum.midpoint.prism.query.TypeFilter; -import com.evolveum.midpoint.prism.query.UndefinedFilter; -import com.evolveum.midpoint.prism.query.ValueFilter; +import com.evolveum.midpoint.prism.query.*; import com.evolveum.midpoint.prism.util.ItemDeltaItem; import com.evolveum.midpoint.prism.util.JavaTypeConverter; import com.evolveum.midpoint.prism.util.ObjectDeltaObject; @@ -83,31 +47,16 @@ import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.Holder; import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.exception.SystemException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectVariableModeType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.QueryInterpretationOfNoValueType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.VariableBindingDefinitionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; /** * @author semancik - * */ public class ExpressionUtil { @@ -203,10 +152,15 @@ public static O convertValue(Class finalExpectedJavaType, Function TypedValue convertVariableValue(TypedValue originalTyped ((Item) valueToConvert).setPrismContext(prismContext); // TODO - or revive? Or make sure prismContext is set here? } if (valueToConvert instanceof ObjectReferenceType) { - ObjectReferenceType reference = ((ObjectReferenceType)valueToConvert).clone(); + ObjectReferenceType reference = ((ObjectReferenceType) valueToConvert).clone(); OperationResult subResult = new OperationResult("Resolve reference"); try { convertedTypeValue = (TypedValue) resolveReference((TypedValue) originalTypedValue, objectResolver, variableName, @@ -281,9 +235,9 @@ public static TypedValue convertVariableValue(TypedValue originalTyped valueToConvert = convertedTypeValue.getValue(); } catch (SchemaException e) { result.addSubresult(subResult); - throw new ExpressionSyntaxException("Schema error during variable "+variableName+" resolution in "+contextDescription+": "+e.getMessage(), e); + throw new ExpressionSyntaxException("Schema error during variable " + variableName + " resolution in " + contextDescription + ": " + e.getMessage(), e); } catch (ObjectNotFoundException e) { - if(ObjectVariableModeType.OBJECT.equals(objectVariableModeType)) { + if (ObjectVariableModeType.OBJECT.equals(objectVariableModeType)) { result.addSubresult(subResult); throw e; } @@ -292,10 +246,10 @@ public static TypedValue convertVariableValue(TypedValue originalTyped throw e; } - if(ObjectVariableModeType.PRISM_REFERENCE.equals(objectVariableModeType)){ + if (ObjectVariableModeType.PRISM_REFERENCE.equals(objectVariableModeType)) { PrismReferenceValue value = reference.asReferenceValue(); - if(valueToConvert instanceof PrismObject) { - value.setObject((PrismObject)valueToConvert); + if (valueToConvert instanceof PrismObject) { + value.setObject((PrismObject) valueToConvert); } convertedTypeValue = (TypedValue) new TypedValue(value, value.getDefinition()); valueToConvert = convertedTypeValue.getValue(); @@ -303,11 +257,11 @@ public static TypedValue convertVariableValue(TypedValue originalTyped } if (valueToConvert instanceof PrismObject) { - convertedTypeValue.setValue(((PrismObject)valueToConvert).asObjectable()); + convertedTypeValue.setValue(((PrismObject) valueToConvert).asObjectable()); return convertedTypeValue; } if (valueToConvert instanceof PrismContainerValue) { - PrismContainerValue cval = ((PrismContainerValue)valueToConvert); + PrismContainerValue cval = ((PrismContainerValue) valueToConvert); Class containerCompileTimeClass = cval.getCompileTimeClass(); if (containerCompileTimeClass == null) { // Dynamic schema. We do not have anything to convert to. Leave it as PrismContainerValue @@ -318,7 +272,7 @@ public static TypedValue convertVariableValue(TypedValue originalTyped return convertedTypeValue; } if (valueToConvert instanceof PrismPropertyValue) { - convertedTypeValue.setValue(((PrismPropertyValue)valueToConvert).getValue()); + convertedTypeValue.setValue(((PrismPropertyValue) valueToConvert).getValue()); return convertedTypeValue; } if (valueToConvert instanceof PrismReferenceValue) { @@ -328,7 +282,7 @@ public static TypedValue convertVariableValue(TypedValue originalTyped } } if (valueToConvert instanceof PrismProperty) { - PrismProperty prop = (PrismProperty)valueToConvert; + PrismProperty prop = (PrismProperty) valueToConvert; PrismPropertyDefinition def = prop.getDefinition(); if (def != null) { if (def.isSingleValue()) { @@ -343,7 +297,7 @@ public static TypedValue convertVariableValue(TypedValue originalTyped } } if (valueToConvert instanceof PrismReference) { - PrismReference ref = (PrismReference)valueToConvert; + PrismReference ref = (PrismReference) valueToConvert; PrismReferenceDefinition def = ref.getDefinition(); if (def != null) { if (def.isSingleValue()) { @@ -357,7 +311,7 @@ public static TypedValue convertVariableValue(TypedValue originalTyped } } if (valueToConvert instanceof PrismContainer) { - PrismContainer container = (PrismContainer)valueToConvert; + PrismContainer container = (PrismContainer) valueToConvert; PrismContainerDefinition def = container.getDefinition(); Class containerCompileTimeClass = container.getCompileTimeClass(); if (containerCompileTimeClass == null) { @@ -393,7 +347,7 @@ public static TypedValue convertVariableValue(TypedValue originalTyped static TypedValue> resolveReference(TypedValue refAndDef, ObjectResolver objectResolver, String varDesc, String contextDescription, Task task, OperationResult result) - throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { ObjectReferenceType ref = (ObjectReferenceType) refAndDef.getValue(); if (ref.getOid() == null) { throw new SchemaException( @@ -433,7 +387,7 @@ static TypedValue> resolveReference(TypedValue ID resolveDefinitionPath(@NotNull ItemPath path, ExpressionVariables variables, PrismContainerDefinition defaultContext, String shortDesc) - throws SchemaException { + throws SchemaException { while (!path.isEmpty() && !path.startsWithName() && !path.startsWithVariable()) { path = path.rest(); } @@ -512,7 +466,7 @@ public static ItemDeltaItem V evaluateExpression(ExpressionVariables variables, PrismContext prismContext, ExpressionType expressionType, ExpressionProfile expressionProfile, ObjectFilter filter, ExpressionFactory expressionFactory, String shortDesc, Task task, OperationResult parentResult) - throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { // TODO refactor after new query engine is implemented ItemDefinition outputDefinition = null; @@ -798,7 +752,7 @@ private static V evaluateExpression(ExpressionVariables v public static V evaluateExpression(Collection> sources, ExpressionVariables variables, D outputDefinition, ExpressionType expressionType, ExpressionProfile expressionProfile, ExpressionFactory expressionFactory, String shortDesc, Task task, OperationResult parentResult) - throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { Expression expression = expressionFactory.makeExpression(expressionType, outputDefinition, expressionProfile, shortDesc, task, parentResult); @@ -814,7 +768,7 @@ public static V evaluateExpress public static V evaluateExpression( ExpressionVariables variables, D outputDefinition, ExpressionType expressionType, ExpressionProfile expressionProfile, ExpressionFactory expressionFactory, String shortDesc, Task task, OperationResult parentResult) - throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { return evaluateExpression(null, variables, outputDefinition, expressionType, expressionProfile, expressionFactory, shortDesc, task, parentResult); } @@ -838,7 +792,7 @@ public static V getExpressionOutputValue(PrismValueDeltaS public static Collection evaluateStringExpression(ExpressionVariables variables, PrismContext prismContext, ExpressionType expressionType, ExpressionProfile expressionProfile, ExpressionFactory expressionFactory, String shortDesc, Task task, OperationResult parentResult) - throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { MutablePrismPropertyDefinition outputDefinition = prismContext.definitionFactory().createPropertyDefinition( ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_STRING); @@ -866,7 +820,7 @@ public static Collection evaluateStringExpression(ExpressionVariables va public static PrismPropertyValue evaluateCondition(ExpressionVariables variables, ExpressionType expressionType, ExpressionProfile expressionProfile, ExpressionFactory expressionFactory, String shortDesc, Task task, OperationResult parentResult) - throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, ExpressionEvaluationException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException { ItemDefinition outputDefinition = expressionFactory.getPrismContext().definitionFactory().createPropertyDefinition( ExpressionConstants.OUTPUT_ELEMENT_NAME, DOMUtil.XSD_BOOLEAN); return (PrismPropertyValue) evaluateExpression(variables, outputDefinition, expressionType, expressionProfile, @@ -1058,10 +1012,10 @@ public static boolean isEmpty(T val) { if (val == null) { return true; } - if (val instanceof String && ((String)val).isEmpty()) { + if (val instanceof String && ((String) val).isEmpty()) { return true; } - if (val instanceof PolyString && ((PolyString)val).isEmpty()) { + if (val instanceof PolyString && ((PolyString) val).isEmpty()) { return true; } return false; @@ -1096,7 +1050,7 @@ public static V convertToPrismValue(T value, ItemDefin return (V) ((PrismContainerValue) value); } else { - throw new ExpressionEvaluationException("Expected Containerable or PrismContainerValue as expression output, got "+value.getClass()); + throw new ExpressionEvaluationException("Expected Containerable or PrismContainerValue as expression output, got " + value.getClass()); } } else { @@ -1104,7 +1058,7 @@ public static V convertToPrismValue(T value, ItemDefin } } - public static Expression,PrismPropertyDefinition> createCondition( + public static Expression, PrismPropertyDefinition> createCondition( ExpressionType conditionExpressionType, ExpressionProfile expressionProfile, ExpressionFactory expressionFactory, @@ -1140,7 +1094,7 @@ public static PrismPropertyDefinition createConditionOutputDefinition(P /** * Used in cases when we do not have a definition. */ - public static ItemDefinition determineDefinitionFromValueClass(PrismContext prismContext, String name, Class valueClass, QName typeQName) { + public static ItemDefinition determineDefinitionFromValueClass(PrismContext prismContext, String name, Class valueClass, QName typeQName) { if (valueClass == null) { return null; } @@ -1165,14 +1119,14 @@ public static ItemDefinition determineDefinitionFromValueClass(PrismContext pri /** * Works only for simple evaluators that do not have any profile settings. */ - public static void checkEvaluatorProfileSimple(ExpressionEvaluator evaluator, ExpressionEvaluationContext context) throws SecurityViolationException { + public static void checkEvaluatorProfileSimple(ExpressionEvaluator evaluator, ExpressionEvaluationContext context) throws SecurityViolationException { ExpressionEvaluatorProfile profile = context.getExpressionEvaluatorProfile(); if (profile == null) { return; // no restrictions } if (profile.getDecision() != AccessDecision.ALLOW) { - throw new SecurityViolationException("Access to evaluator "+evaluator.shortDebugDump()+ - " not allowed (expression profile: "+context.getExpressionProfile().getIdentifier()+") in "+context.getContextDescription()); + throw new SecurityViolationException("Access to evaluator " + evaluator.shortDebugDump() + + " not allowed (expression profile: " + context.getExpressionProfile().getIdentifier() + ") in " + context.getContextDescription()); } } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/NameResolutionHelper.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/NameResolutionHelper.java index 7cb7d13dc5b..fd08b65457f 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/NameResolutionHelper.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/helpers/NameResolutionHelper.java @@ -103,11 +103,11 @@ public void resolveNamesIfRequested(Session session, List getPathsToResolve(Collection> options) { - final UniformItemPath EMPTY_PATH = prismContext.emptyPath(); + final UniformItemPath emptyPath = prismContext.emptyPath(); List rv = new ArrayList<>(); for (SelectorOptions option : CollectionUtils.emptyIfNull(options)) { if (GetOperationOptions.isResolveNames(option.getOptions())) { - rv.add(option.getItemPath(EMPTY_PATH)); + rv.add(option.getItemPath(emptyPath)); } } return rv; diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPhotoAssignment.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPhotoAssignment.java index 2ee3377e80c..4662b6286ea 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPhotoAssignment.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPhotoAssignment.java @@ -7,26 +7,21 @@ package com.evolveum.midpoint.testing.story; +import java.io.File; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.TestResource; import com.evolveum.midpoint.test.asserter.UserAsserter; -import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.io.File; - -/** - * - */ -@SuppressWarnings("FieldCanBeLocal") -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestPhotoAssignment extends AbstractStoryTest { @@ -59,7 +54,6 @@ protected PrismObject getDefaultActor() { @Test public void test100AssignJoeCard() throws Exception { - TestPhotoAssignment.class.getName(); Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java index ed369f339ef..cfbea40d5c6 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java @@ -124,7 +124,7 @@ public void test101jiraAssignResourceNoneEnforcement() throws Exception { PrismObject service = getObject(ServiceType.class, SERVICE_JIRA_OID); display("Service magazine after", service); assertNotNull("No magazine service", service); - assertAssignedResource(ServiceType.class, SERVICE_JIRA_OID, RESOURCE_DUMMY_CLASSIFIER_OID, task, result); + assertAssignedResource(ServiceType.class, SERVICE_JIRA_OID, RESOURCE_DUMMY_CLASSIFIER_OID, result); assertNoLinkedAccount(service); } @@ -257,7 +257,7 @@ public void test215githubAssignResourceNoneEnforcement() throws Exception { PrismObject service = getObject(ServiceType.class, SERVICE_GITHUB_OID); display("Service github after", service); assertNotNull("No github service", service); - assertAssignedResource(ServiceType.class, SERVICE_GITHUB_OID, RESOURCE_DUMMY_CLASSIFIER_OID, task, result); + assertAssignedResource(ServiceType.class, SERVICE_GITHUB_OID, RESOURCE_DUMMY_CLASSIFIER_OID, result); assertNoLinkedAccount(service); } @@ -285,7 +285,7 @@ public void test220linkAccountGithubAndFixIntent() throws Exception { PrismObject serviceGithubAfter = getObject(ServiceType.class, SERVICE_GITHUB_OID); display("Service github after", serviceGithubAfter); assertNotNull("No github service", serviceGithubAfter); - assertAssignedResource(ServiceType.class, SERVICE_GITHUB_OID, RESOURCE_DUMMY_CLASSIFIER_OID, task, result); + assertAssignedResource(ServiceType.class, SERVICE_GITHUB_OID, RESOURCE_DUMMY_CLASSIFIER_OID, result); PrismAsserts.assertPropertyValue(serviceGithubAfter, ItemPath.create(ServiceType.F_EXTENSION, F_ACCOUNT_NAME), ACCOUNT_DUMMY_GITHUB_USERNAME); assertLinks(serviceGithubAfter, 1); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java index 454f47d825c..3b5edddf32b 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java @@ -98,8 +98,6 @@ public void test001testImportBaseUsers() throws Exception { waitForTaskFinish(TASK_IMPORT_BASE_USERS_OID, true, 30000); -// waitForTaskNextRun(TASK_IMPORT_BASE_USERS_OID, true, 20000, true); - Task taskAfter = taskManager.getTaskWithResult(TASK_IMPORT_BASE_USERS_OID, result); display("Task after test001testImportBaseUsers:", taskAfter); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/AbstractLdapTest.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/AbstractLdapTest.java index 427c2c02e65..c4d85e914ed 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/AbstractLdapTest.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/AbstractLdapTest.java @@ -7,16 +7,12 @@ package com.evolveum.midpoint.testing.story.ldap; - -import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertEquals; import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.namespace.QName; import org.opends.server.types.DirectoryException; @@ -26,7 +22,6 @@ import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; -import com.evolveum.midpoint.util.exception.PolicyViolationException; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ItemDelta; @@ -40,34 +35,22 @@ import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.testing.story.AbstractStoryTest; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * Testing dependencies: * There are two meta-roles for orgs. * Org Metarole contains two inducements, one for creating organizationalUnit (intent=ou) and one for creating groupOfUniqueNames (intent=group) in ldap. * group depends on ou (since it is created in ou) - * + *

* Org Metarole VIP is very similar it also contains two inducements, one for creating (intent=ou-vip) and one for creating groupOfUniqueNames (intent=group-vip) in ldap. * group-vip depends on ou-cip (since it is created in ou-vip) * * @author michael gruber - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLdapTest extends AbstractStoryTest { @@ -107,9 +90,7 @@ protected ObjectDelta createAssignmentOrgDelta(String orgOid, String ro PrismContainer extension, ActivationType activationType, boolean add) throws SchemaException { Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(roleOid, refType, relation, extension, activationType, add))); - ObjectDelta userDelta = prismContext.deltaFactory().object().createModifyDelta(orgOid, modifications, OrgType.class - ); - return userDelta; + return prismContext.deltaFactory().object().createModifyDelta(orgOid, modifications, OrgType.class); } protected void assignRoleToOrg(String orgOid, String roleOid, Task task, OperationResult result) @@ -140,6 +121,7 @@ protected void unassignRoleFromOrg(String orgOid, String roleOid, ActivationType // TODO: maybe a replacement for MidpointAsserts.assertNotAssigned() // it can be used not only for user + @UnusedTestElement protected void assertNotAssigned(PrismObject focus, String targetOid, QName refType) { F focusType = focus.asObjectable(); for (AssignmentType assignmentType : focusType.getAssignment()) { @@ -155,12 +137,16 @@ protected void assertNotAssigned(PrismObject focus, Str } } - protected void assertLdapConnectorInstances(int expectedConnectorInstances) throws NumberFormatException, IOException, InterruptedException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertLdapConnectorInstances(int expectedConnectorInstances) + throws NumberFormatException, SchemaException, ObjectNotFoundException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { assertLdapConnectorInstances(expectedConnectorInstances, expectedConnectorInstances); } - protected void assertLdapConnectorInstances(int expectedConnectorInstancesMin, int expectedConnectorInstancesMax) throws NumberFormatException, IOException, InterruptedException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - TestLdapSyncMassive.class.getName(); + protected void assertLdapConnectorInstances( + int expectedConnectorInstancesMin, int expectedConnectorInstancesMax) + throws NumberFormatException, SchemaException, ObjectNotFoundException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = getTestTask(); OperationResult result = task.getResult(); List stats = provisioningService.getConnectorOperationalStatus(getLdapResourceOid(), task, result); @@ -173,17 +159,16 @@ protected void assertLdapConnectorInstances(int expectedConnectorInstancesMin, i int actualConnectorInstances = stat.getPoolStatusNumIdle() + stat.getPoolStatusNumActive(); if (actualConnectorInstances < expectedConnectorInstancesMin) { - fail("Number of LDAP connector instances too low: "+actualConnectorInstances+", expected at least "+expectedConnectorInstancesMin); + fail("Number of LDAP connector instances too low: " + actualConnectorInstances + ", expected at least " + expectedConnectorInstancesMin); } if (actualConnectorInstances > expectedConnectorInstancesMax) { - fail("Number of LDAP connector instances too high: "+actualConnectorInstances+", expected at most "+expectedConnectorInstancesMax); + fail("Number of LDAP connector instances too high: " + actualConnectorInstances + ", expected at most " + expectedConnectorInstancesMax); } } - protected void assertLdapAccounts(int expectedNumber) throws DirectoryException { - List entries = openDJController.search("objectclass="+OBJECTCLASS_INETORGPERSON); - assertEquals("Wrong number of LDAP accounts ("+OBJECTCLASS_INETORGPERSON+")", expectedNumber, entries.size()); + List entries = openDJController.search("objectclass=" + OBJECTCLASS_INETORGPERSON); + assertEquals("Wrong number of LDAP accounts (" + OBJECTCLASS_INETORGPERSON + ")", expectedNumber, entries.size()); } protected int getNumberOfLdapAccounts() { @@ -191,7 +176,7 @@ protected int getNumberOfLdapAccounts() { } protected Entry getLdapEntryByUid(String uid) throws DirectoryException { - return openDJController.searchSingle("uid="+uid); + return openDJController.searchSingle("uid=" + uid); } protected void assertCn(Entry entry, String expectedValue) { From ed8e7b8652de43e9879f6ccc15a730c1db25949a Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Fri, 6 Mar 2020 01:19:23 +0100 Subject: [PATCH 07/55] Adapt and fix TestThresholds et al These tests were adapted to recent changes in counting of objects in various synchronization situations (see the commit for MID-5406). Also, treatment of disabled objects was fixed: the policy rule was not quite correct and so was LDIF import of changes. --- .../xml/ns/public/common/common-core-3.xsd | 2 +- .../midpoint/test/ldap/OpenDJController.java | 32 ++++--- .../model/impl/lens/LensElementContext.java | 36 ++------ .../model/impl/lens/LensFocusContext.java | 5 +- .../impl/lens/LensProjectionContext.java | 14 +-- .../intest/mapping/TestMappingInbound.java | 2 +- .../test/AbstractModelIntegrationTest.java | 4 +- .../test/AbstractIntegrationTest.java | 4 +- .../midpoint/task/api/TaskManager.java | 2 +- .../quartzimpl/TaskManagerQuartzImpl.java | 2 +- .../testing/story/TestThresholds.java | 87 ++++++++++++++----- .../story/TestThresholdsLiveSyncFull.java | 24 +++-- .../story/TestThresholdsLiveSyncSimulate.java | 21 +++-- .../story/TestThresholdsReconFull.java | 41 +++++---- .../story/TestThresholdsReconSimulate.java | 35 +++++--- .../role-policy-rule-change-activation.xml | 4 +- .../thresholds/task-opendj-livesync-full.xml | 3 +- .../task-opendj-livesync-simulate.xml | 1 - .../thresholds/task-opendj-reconcile-full.xml | 9 +- ...task-opendj-reconcile-simulate-execute.xml | 1 - .../task-opendj-reconcile-simulate.xml | 1 - 21 files changed, 193 insertions(+), 137 deletions(-) diff --git a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd index b892d733c21..7534e40b98b 100755 --- a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd +++ b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd @@ -5553,7 +5553,7 @@ AssignmentType.target AssignmentType.target.help - tns:FocusType + tns:AssignmentHolderType diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/OpenDJController.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/OpenDJController.java index 47f01b7bcd6..6195f33bdcf 100755 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/OpenDJController.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/ldap/OpenDJController.java @@ -26,6 +26,7 @@ import org.apache.commons.io.IOUtils; import org.apache.commons.lang.ArrayUtils; import org.apache.commons.lang.Validate; +import org.jetbrains.annotations.NotNull; import org.opends.messages.Message; import org.opends.messages.MessageBuilder; import org.opends.server.config.ConfigException; @@ -883,28 +884,37 @@ public ChangeRecordEntry executeLdifChange(File file) throws IOException, LDIFEx LDIFReader ldifReader = new LDIFReader(importConfig); ChangeRecordEntry entry = ldifReader.readChangeRecord(false); - ModifyOperation modifyOperation = getInternalConnection() - .processModify((ModifyChangeRecordEntry) entry); + return executeChangeInternal(entry); + } + + @NotNull + private ChangeRecordEntry executeChangeInternal(ChangeRecordEntry entry) { + ModifyOperation modifyOperation = getInternalConnection().processModify((ModifyChangeRecordEntry) entry); if (ResultCode.SUCCESS != modifyOperation.getResultCode()) { - throw new RuntimeException("LDAP operation error: "+modifyOperation.getResultCode()+": "+modifyOperation.getErrorMessage()); + throw new RuntimeException("LDAP operation error: " + modifyOperation.getResultCode() + ": " + modifyOperation.getErrorMessage()); } return entry; } + public void executeLdifChanges(File file) throws IOException, LDIFException { + LDIFImportConfig importConfig = new LDIFImportConfig(file.getPath()); + LDIFReader ldifReader = new LDIFReader(importConfig); + for (;;) { + ChangeRecordEntry entry = ldifReader.readChangeRecord(false); + if (entry == null) { + break; + } + executeChangeInternal(entry); + } + } + public ChangeRecordEntry executeLdifChange(String ldif) throws IOException, LDIFException { InputStream ldifInputStream = IOUtils.toInputStream(ldif, StandardCharsets.UTF_8); LDIFImportConfig importConfig = new LDIFImportConfig(ldifInputStream); LDIFReader ldifReader = new LDIFReader(importConfig); ChangeRecordEntry entry = ldifReader.readChangeRecord(false); - - ModifyOperation modifyOperation = getInternalConnection() - .processModify((ModifyChangeRecordEntry) entry); - - if (ResultCode.SUCCESS != modifyOperation.getResultCode()) { - throw new RuntimeException("LDAP operation error: "+modifyOperation.getResultCode()+": "+modifyOperation.getErrorMessage()); - } - return entry; + return executeChangeInternal(entry); } public ChangeRecordEntry modifyReplace(String entryDn, String attributeName, String value) throws IOException, LDIFException { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java index ba5355cdc3e..f9e45fa0853 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensElementContext.java @@ -339,45 +339,25 @@ public void addToPendingAssignmentPolicyStateModifications(@NotNull AssignmentTy pendingAssignmentPolicyStateModifications.computeIfAbsent(spec, k -> new ArrayList<>()).add(modification); } - public boolean isAdd() { - if (ObjectDelta.isAdd(getPrimaryDelta())) { - return true; - } - if (ObjectDelta.isAdd(getSecondaryDelta())) { - return true; - } - return false; - } + public abstract boolean isAdd(); public boolean isModify() { - if (ObjectDelta.isModify(getPrimaryDelta())) { - return true; - } - if (ObjectDelta.isModify(getSecondaryDelta())) { - return true; - } - return false; + // TODO I'm not sure why isModify checks both primary and secondary deltas for focus context, while + // isAdd and isDelete care only for the primary delta. + return ObjectDelta.isModify(getPrimaryDelta()) || ObjectDelta.isModify(getSecondaryDelta()); } - public boolean isDelete() { - if (ObjectDelta.isDelete(getPrimaryDelta())) { - return true; - } - if (ObjectDelta.isDelete(getSecondaryDelta())) { - return true; - } - return false; - } + public abstract boolean isDelete(); @NotNull public SimpleOperationName getOperation() { if (isAdd()) { return SimpleOperationName.ADD; - } - if (isDelete()) { + } else if (isDelete()) { return SimpleOperationName.DELETE; + } else { + return SimpleOperationName.MODIFY; } - return SimpleOperationName.MODIFY; } @NotNull diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensFocusContext.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensFocusContext.java index 30ef72357de..58a13b23884 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensFocusContext.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensFocusContext.java @@ -102,14 +102,13 @@ public ObjectDelta getProjectionWavePrimaryDelta() throws SchemaException { } public boolean isDelete() { - return getPrimaryDelta() != null && getPrimaryDelta().isDelete(); + return ObjectDelta.isDelete(getPrimaryDelta()); } public boolean isAdd() { - return getPrimaryDelta() != null && getPrimaryDelta().isAdd(); + return ObjectDelta.isAdd(getPrimaryDelta()); } - @Override public ObjectDelta getSecondaryDelta() { try { diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensProjectionContext.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensProjectionContext.java index 32f2f8437f3..f6403ba90d3 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensProjectionContext.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/LensProjectionContext.java @@ -406,10 +406,11 @@ public void addAccountSyncDelta(ObjectDelta delta) throws SchemaExce public boolean isAdd() { if (synchronizationPolicyDecision == SynchronizationPolicyDecision.ADD) { return true; - } else if (synchronizationPolicyDecision != null){ + } else if (synchronizationPolicyDecision != null) { return false; + } else { + return ObjectDelta.isAdd(getPrimaryDelta()) || ObjectDelta.isAdd(getSecondaryDelta()); } - return super.isAdd(); } public boolean isModify() { @@ -417,8 +418,9 @@ public boolean isModify() { return true; } else if (synchronizationPolicyDecision != null) { return false; + } else { + return super.isModify(); } - return super.isModify(); } public boolean isDelete() { @@ -426,11 +428,9 @@ public boolean isDelete() { return true; } else if (synchronizationPolicyDecision != null) { return false; + } else { + return ObjectDelta.isDelete(syncDelta) || ObjectDelta.isDelete(getPrimaryDelta()) || ObjectDelta.isDelete(getSecondaryDelta()); } - if (syncDelta != null && syncDelta.isDelete()) { - return true; - } - return super.isDelete(); } public ResourceType getResource() { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java index 7ee0521a493..f991e41a4ef 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java @@ -378,7 +378,7 @@ public void test300DeleteDummyTeaGreenAccountMancomb() throws Exception { display("Dummy (tea green) resource", getDummyResource(RESOURCE_DUMMY_TEA_GREEN_NAME).debugDump()); // Make sure we have steady state - waitForTaskResume(TASK_LIVE_SYNC_DUMMY_TEA_GREEN_OID, false, 20000); + resumeTaskAndWaitForNextFinish(TASK_LIVE_SYNC_DUMMY_TEA_GREEN_OID, false, 20000); waitForSyncTaskNextRun(); // THEN diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index 2f92537f920..3c1f8e7e215 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -3519,7 +3519,7 @@ private static OperationResult getSubresult(OperationResult result, boolean chec return result; } - protected OperationResult waitForTaskResume(final String taskOid, final boolean checkSubresult, final int timeout) throws Exception { + protected OperationResult resumeTaskAndWaitForNextFinish(final String taskOid, final boolean checkSubresult, final int timeout) throws Exception { final OperationResult waitResult = new OperationResult(AbstractIntegrationTest.class + ".waitForTaskResume"); Task origTask = taskManager.getTaskWithResult(taskOid, waitResult); @@ -3569,7 +3569,7 @@ public void timeout() { } } }; - IntegrationTestTools.waitFor("Waiting for task " + origTask + " resume", checker, timeout, DEFAULT_TASK_SLEEP_TIME); + IntegrationTestTools.waitFor("Waiting for resumed task " + origTask + " finish", checker, timeout, DEFAULT_TASK_SLEEP_TIME); Task freshTask = taskManager.getTaskWithResult(origTask.getOid(), waitResult); logger.debug("Final task:\n{}", freshTask.debugDump()); diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index c4dcdab15ca..c5e80c74f81 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -2882,8 +2882,8 @@ protected void setGlobalTracingOverrideAll(@NotNull TracingProfileType profile) taskManager.setGlobalTracingOverride(Arrays.asList(TracingRootType.values()), profile); } - protected void removeGlobalTracingOverride() { - taskManager.removeGlobalTracingOverride(); + protected void unsetGlobalTracingOverride() { + taskManager.unsetGlobalTracingOverride(); } protected Consumer> workerThreadsCustomizer(int threads) { diff --git a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java index cb8510e7a85..16e26239b43 100644 --- a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java +++ b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java @@ -785,7 +785,7 @@ String recordTaskThreadsDump(String taskOid, String cause, OperationResult paren void setGlobalTracingOverride(@NotNull Collection roots, @NotNull TracingProfileType profile); // EXPERIMENTAL - void removeGlobalTracingOverride(); + void unsetGlobalTracingOverride(); /** * @return true if we consider this node to be "up" (alive). This is determined by looking at operational state diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java index 4cfe84bedec..ba400b55882 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java @@ -2633,7 +2633,7 @@ public void setGlobalTracingOverride(@NotNull Collection roots, } @Override - public void removeGlobalTracingOverride() { + public void unsetGlobalTracingOverride() { globalTracingOverride = null; } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java index 454f47d825c..458288f5bf9 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholds.java @@ -10,6 +10,13 @@ import static org.testng.Assert.assertNotNull; import java.io.File; +import java.util.List; + +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; +import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; +import com.evolveum.midpoint.util.exception.ObjectNotFoundException; +import com.evolveum.midpoint.util.exception.SchemaException; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -45,14 +52,14 @@ public abstract class TestThresholds extends AbstractStoryTest { private static final String ROLE_POLICY_RULE_CREATE_OID = "00000000-role-0000-0000-999111111112"; private static final File ROLE_POLICY_RULE_CHANGE_ACTIVATION_FILE = new File(TEST_DIR, "role-policy-rule-change-activation.xml"); - protected static final String ROLE_POLICY_RULE_CHANGE_ACTIVATION_OID = "00000000-role-0000-0000-999111111223"; + private static final String ROLE_POLICY_RULE_CHANGE_ACTIVATION_OID = "00000000-role-0000-0000-999111111223"; private static final File TASK_IMPORT_BASE_USERS_FILE = new File(TEST_DIR, "task-opendj-import-base-users.xml"); private static final String TASK_IMPORT_BASE_USERS_OID = "fa25e6dc-a858-11e7-8ebc-eb2b71ecce1d"; private static final int TASK_IMPORT_TIMEOUT = 60000; - protected int getDefaultUsers() { + int getDefaultUsers() { return 6; } @@ -88,6 +95,9 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(getTaskFile(), initResult); } + /** + * Imports base users in an auxiliary task ("import base users"). + */ @Test public void test001testImportBaseUsers() throws Exception { OperationResult result = createOperationResult(); @@ -127,14 +137,19 @@ protected int getNumberOfUsers() { return super.getNumberOfUsers() + getDefaultUsers(); } + /** + * Assigns the rule of "Stop after 4 created users" to the main task. + */ @Test - public void test100assignPolicyRuleCreateToTask() throws Exception { - // WHEN + public void test100AssignCreationLimitToTask() throws Exception { + Task task = createPlainTask(); OperationResult result = task.getResult(); + + when(); assignRole(TaskType.class, getTaskOid(), ROLE_POLICY_RULE_CREATE_OID, task, result); - //THEN + then(); PrismObject taskAfter = getObject(TaskType.class, getTaskOid()); display("Task after:", taskAfter); assertAssignments(taskAfter, 1); @@ -143,20 +158,23 @@ public void test100assignPolicyRuleCreateToTask() throws Exception { } + /** + * Runs the main task and checks if it stopped after processing expected number of users. + */ @Test - public void test110importAccounts() throws Exception { + public void test110ImportAccounts() throws Exception { Task task = createPlainTask(); OperationResult result = task.getResult(); openDJController.addEntriesFromLdifFile(LDIF_CREATE_USERS_FILE); assertUsers(getNumberOfUsers()); - //WHEN + when(); - OperationResult reconResult = waitForTaskResume(getTaskOid(), false, TASK_IMPORT_TIMEOUT); + OperationResult reconResult = resumeTaskAndWaitForNextFinish(getTaskOid(), false, TASK_IMPORT_TIMEOUT); assertFailure(reconResult); - //THEN + then(); assertUsers(getProcessedUsers() + getNumberOfUsers()); assertTaskExecutionStatus(getTaskOid(), TaskExecutionStatus.SUSPENDED); @@ -164,37 +182,52 @@ public void test110importAccounts() throws Exception { assertSynchronizationStatisticsAfterImport(taskAfter); } + /** + * Adds more users. Runs the main task again and checks if it again stopped after processing expected number of users. + */ @Test - public void test111importAccountsAgain() throws Exception { + public void test111ImportAccountsAgain() throws Exception { Task task = createPlainTask(); OperationResult result = task.getResult(); + given(); openDJController.addEntriesFromLdifFile(LDIF_CREATE_USERS_NEXT_FILE); - assertUsers(getNumberOfUsers() + getProcessedUsers()); - //WHEN + clearTaskOperationalStats(result); + when(); - OperationResult reconResult = waitForTaskResume(getTaskOid(), false, TASK_IMPORT_TIMEOUT); + OperationResult reconResult = resumeTaskAndWaitForNextFinish(getTaskOid(), false, TASK_IMPORT_TIMEOUT); assertFailure(reconResult); - //THEN + then(); assertUsers(getProcessedUsers() * 2 + getNumberOfUsers()); assertTaskExecutionStatus(getTaskOid(), TaskExecutionStatus.SUSPENDED); Task taskAfter = taskManager.getTaskWithResult(getTaskOid(), result); assertSynchronizationStatisticsAfterSecondImport(taskAfter); + } + private void clearTaskOperationalStats(OperationResult result) throws SchemaException, ObjectAlreadyExistsException, + ObjectNotFoundException { + List> modifications = deltaFor(TaskType.class) + .item(TaskType.F_OPERATION_STATS).replace() + .asItemDeltas(); + repositoryService.modifyObject(TaskType.class, getTaskOid(), modifications, result); } + /** + * Changes the rule to "Stop after having 2 users with changed activation/administrativeStatus". + */ @Test - public void test500changeTaskPolicyRule() throws Exception { - //WHEN + public void test500AssignModificationLimitToTask() throws Exception { Task task = createPlainTask(); OperationResult result = task.getResult(); + + when(); unassignRole(TaskType.class, getTaskOid(), ROLE_POLICY_RULE_CREATE_OID, task, result); assignRole(TaskType.class, getTaskOid(), ROLE_POLICY_RULE_CHANGE_ACTIVATION_OID, task, result); - //THEN + then(); PrismObject taskAfter = getObject(TaskType.class, getTaskOid()); display("Task after:", taskAfter); assertAssignments(taskAfter, 1); @@ -202,24 +235,30 @@ public void test500changeTaskPolicyRule() throws Exception { assertTaskExecutionStatus(getTaskOid(), TaskExecutionStatus.SUSPENDED); } + /** + * Disables accounts for users1..6 on the resource. Expects to stop after processing 2 of them. + */ @Test - public void test520changeActivationThreeAccounts() throws Exception { + public void test520ImportDisabledAccounts() throws Exception { OperationResult result = createOperationResult(); - //GIVEN - openDJController.executeLdifChange(LDIF_CHANGE_ACTIVATION_FILE); + given(); + openDJController.executeLdifChanges(LDIF_CHANGE_ACTIVATION_FILE); + clearTaskOperationalStats(result); - //WHEN when(); - OperationResult reconResult = waitForTaskResume(getTaskOid(), false, 20000); + OperationResult reconResult = resumeTaskAndWaitForNextFinish(getTaskOid(), false, 20000); assertFailure(reconResult); - //THEN - + then(); Task taskAfter = taskManager.getTaskWithResult(getTaskOid(), result); assertTaskExecutionStatus(getTaskOid(), TaskExecutionStatus.SUSPENDED); assertSynchronizationStatisticsActivation(taskAfter); } + + void dumpSynchronizationInformation(SynchronizationInformationType synchronizationInformation) { + display("Synchronization information", SynchronizationInformation.format(synchronizationInformation)); + } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncFull.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncFull.java index 4bdaf0c8ec5..3094ee9c73b 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncFull.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncFull.java @@ -10,6 +10,8 @@ import java.io.File; +import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; + import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -45,6 +47,7 @@ protected int getProcessedUsers() { @Override protected void assertSynchronizationStatisticsAfterImport(Task taskAfter) throws Exception { SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); assertSyncToken(taskAfter, 4, taskAfter.getResult()); @@ -53,7 +56,7 @@ protected void assertSynchronizationStatisticsAfterImport(Task taskAfter) throws assertEquals(syncInfo.getCountLinked(), 0); assertEquals(syncInfo.getCountUnlinked(), 0); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + assertEquals(syncInfo.getCountUnmatchedAfter(), 1); // this is the one that failed assertEquals(syncInfo.getCountDeletedAfter(), 0); assertEquals(syncInfo.getCountLinkedAfter(), getProcessedUsers()); assertEquals(syncInfo.getCountUnlinkedAfter(), 0); @@ -61,18 +64,21 @@ protected void assertSynchronizationStatisticsAfterImport(Task taskAfter) throws } protected void assertSynchronizationStatisticsActivation(Task taskAfter) { - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnmatched(), 3); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountDeleted(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountLinked(), 8); // this is because LiveSync re-processes changes by default (FIXME) - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnlinked(), 0); + SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); + + // It's actually not much clear how these numbers are obtained. The task processes various (yet unprocessed) changes + // and stops after seeing third disabled account. + assertEquals(syncInfo.getCountUnmatched(), 3); + assertEquals(syncInfo.getCountDeleted(), 0); + assertEquals(syncInfo.getCountLinked(), 9); + assertEquals(syncInfo.getCountUnlinked(), 0); } - /* (non-Javadoc) - * @see com.evolveum.midpoint.testing.story.TestThresholds#assertSynchronizationStatisticsAfterSecondImport(com.evolveum.midpoint.task.api.Task) - */ @Override protected void assertSynchronizationStatisticsAfterSecondImport(Task taskAfter) throws Exception { SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); assertSyncToken(taskAfter, 4, taskAfter.getResult()); @@ -81,7 +87,7 @@ protected void assertSynchronizationStatisticsAfterSecondImport(Task taskAfter) assertEquals(syncInfo.getCountLinked(), 4); // this is because LiveSync re-processes changes by default (FIXME) assertEquals(syncInfo.getCountUnlinked(), 0); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + assertEquals(syncInfo.getCountUnmatchedAfter(), 1); // this is the one that failed assertEquals(syncInfo.getCountDeletedAfter(), 0); assertEquals(syncInfo.getCountLinkedAfter(), 8); // this is because LiveSync re-processes changes by default (FIXME) assertEquals(syncInfo.getCountUnlinkedAfter(), 0); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncSimulate.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncSimulate.java index 304e42c3d60..15e7a315e12 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncSimulate.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsLiveSyncSimulate.java @@ -45,10 +45,12 @@ protected int getProcessedUsers() { @Override protected void assertSynchronizationStatisticsAfterImport(Task taskAfter) throws Exception { SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); assertSyncToken(taskAfter, 4, taskAfter.getResult()); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + // user5, user6, user7, user8, user9 (why not user4? -- because token is preset to 4) + assertEquals(syncInfo.getCountUnmatchedAfter(), 5); assertEquals(syncInfo.getCountDeletedAfter(), 0); assertEquals(syncInfo.getCountLinkedAfter(), 0); assertEquals(syncInfo.getCountUnlinkedAfter(), 0); @@ -56,10 +58,15 @@ protected void assertSynchronizationStatisticsAfterImport(Task taskAfter) throws } protected void assertSynchronizationStatisticsActivation(Task taskAfter) { - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnmatched(), 3); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountDeleted(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountLinked(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnlinked(), 0); + SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); + + // new users: user5, user6, user7, user8, user9, user10, user11, user12, user13, user14, user15 (11 users) + assertEquals(syncInfo.getCountUnmatched(), 11); + assertEquals(syncInfo.getCountDeleted(), 0); + // existing users: user1, user2 (disabled - passes), user3 (disabled - fails) -- these users were created during initial import + assertEquals(syncInfo.getCountLinked(), 3); // 2 + 1 + assertEquals(syncInfo.getCountUnlinked(), 0); } /* (non-Javadoc) @@ -68,10 +75,12 @@ protected void assertSynchronizationStatisticsActivation(Task taskAfter) { @Override protected void assertSynchronizationStatisticsAfterSecondImport(Task taskAfter) throws Exception { SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); assertSyncToken(taskAfter, 4, taskAfter.getResult()); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + // user5, user6, user7, user8, user9 + assertEquals(syncInfo.getCountUnmatchedAfter(), 5); assertEquals(syncInfo.getCountDeletedAfter(), 0); assertEquals(syncInfo.getCountLinkedAfter(), 0); assertEquals(syncInfo.getCountUnlinkedAfter(), 0); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java index 5c64d3ab314..5861da8a0cc 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconFull.java @@ -11,6 +11,10 @@ import java.io.File; +import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; + +import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; + import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -62,7 +66,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @Test - public void test600changeTaskPolicyRule() throws Exception { + public void test600ChangeTaskPolicyRule() throws Exception { //WHEN Task task = createPlainTask(); OperationResult result = task.getResult(); @@ -77,12 +81,12 @@ public void test600changeTaskPolicyRule() throws Exception { } @Test - public void test610testFullRecon() throws Exception { + public void test610TestFullRecon() throws Exception { OperationResult result = createOperationResult(); //WHEN when(); - OperationResult reconResult = waitForTaskResume(TASK_RECONCILE_OPENDJ_SIMULATE_EXECUTE_OID, true, 20000); + OperationResult reconResult = resumeTaskAndWaitForNextFinish(TASK_RECONCILE_OPENDJ_SIMULATE_EXECUTE_OID, true, 20000); assertSuccess(reconResult); //THEN @@ -95,7 +99,7 @@ public void test610testFullRecon() throws Exception { } @Test - public void test611testFullRecon() throws Exception { + public void test611TestFullRecon() throws Exception { OperationResult result = createOperationResult(); openDJController.delete("uid=user10,ou=People,dc=example,dc=com"); @@ -151,7 +155,7 @@ protected void assertSynchronizationStatisticsAfterImport(Task taskAfter) { assertEquals(syncInfo.getCountLinked(), getDefaultUsers()); assertEquals(syncInfo.getCountUnlinked(), 0); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + assertEquals(syncInfo.getCountUnmatchedAfter(), 1); // There is 1 unmatched because it's recorded after "stop" policy rule triggered assertEquals(syncInfo.getCountDeleted(), 0); assertEquals(syncInfo.getCountLinkedAfter(), getDefaultUsers() + getProcessedUsers()); assertEquals(syncInfo.getCountUnlinked(), 0); @@ -164,9 +168,6 @@ private void assertSynchronizationStatisticsFull(Task taskAfter) { } - /* (non-Javadoc) - * @see com.evolveum.midpoint.testing.story.TestThresholds#assertSynchronizationStatisticsAfterSecondImport(com.evolveum.midpoint.task.api.Task) - */ @Override protected void assertSynchronizationStatisticsAfterSecondImport(Task taskAfter) { IterativeTaskInformationType infoType = taskAfter.getStoredOperationStats().getIterativeTaskInformation(); @@ -179,7 +180,7 @@ protected void assertSynchronizationStatisticsAfterSecondImport(Task taskAfter) assertEquals(syncInfo.getCountLinked(), getDefaultUsers() + getProcessedUsers()); assertEquals(syncInfo.getCountUnlinked(), 0); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + assertEquals(syncInfo.getCountUnmatchedAfter(), 1); // There is 1 unmatched because it's recorded after "stop" policy rule triggered assertEquals(syncInfo.getCountDeleted(), 0); assertEquals(syncInfo.getCountLinkedAfter(), getDefaultUsers() + getProcessedUsers() * 2); assertEquals(syncInfo.getCountUnlinked(), 0); @@ -188,15 +189,21 @@ protected void assertSynchronizationStatisticsAfterSecondImport(Task taskAfter) protected void assertSynchronizationStatisticsActivation(Task taskAfter) { IterativeTaskInformationType infoType = taskAfter.getStoredOperationStats().getIterativeTaskInformation(); assertEquals(infoType.getTotalFailureCount(), 1); + display("Iterative task information", IterativeTaskInformation.format(infoType)); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnmatched(), 3); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountDeleted(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountLinked(), 14); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnlinked(), 0); + SynchronizationInformationType synchronizationInformation = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(synchronizationInformation); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnmatchedAfter(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountDeleted(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountLinked(), 14); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnlinked(), 0); + assertEquals(synchronizationInformation.getCountUnmatched(), 0); + assertEquals(synchronizationInformation.getCountDeleted(), 0); + // 1. gibbs, 2. barbossa, 3. beckett (unchanged), 4. user1, 5. user2 (disabled), 6. user3 (tried to be disabled but failed because of the rule) + assertEquals(synchronizationInformation.getCountLinked(), 6); + assertEquals(synchronizationInformation.getCountUnlinked(), 0); + + assertEquals(synchronizationInformation.getCountUnmatchedAfter(), 0); + assertEquals(synchronizationInformation.getCountDeleted(), 0); + assertEquals(synchronizationInformation.getCountLinked(), 6); + assertEquals(synchronizationInformation.getCountUnlinked(), 0); } + } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconSimulate.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconSimulate.java index 6858c459461..79ad5095709 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconSimulate.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestThresholdsReconSimulate.java @@ -49,15 +49,18 @@ protected void assertSynchronizationStatisticsAfterImport(Task taskAfter) { assertEquals(infoType.getTotalFailureCount(), 1); SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); + // user4, user5, user6, user7, user8 assertEquals(syncInfo.getCountUnmatched(), 5); assertEquals(syncInfo.getCountDeleted(), 0); + // jgibbs, hbarbossa, jbeckett, user1, user2, user3 assertEquals(syncInfo.getCountLinked(), getDefaultUsers()); assertEquals(syncInfo.getCountUnlinked(), 0); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + assertEquals(syncInfo.getCountUnmatchedAfter(), 5); assertEquals(syncInfo.getCountDeletedAfter(), 0); - assertEquals(syncInfo.getCountLinkedAfter(), 0); + assertEquals(syncInfo.getCountLinkedAfter(), getDefaultUsers()); assertEquals(syncInfo.getCountUnlinkedAfter(), 0); } @@ -70,15 +73,18 @@ protected void assertSynchronizationStatisticsAfterSecondImport(Task taskAfter) assertEquals(infoType.getTotalFailureCount(), 1); SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); + // user4, user5, user6, user7, user8 assertEquals(syncInfo.getCountUnmatched(), 5); assertEquals(syncInfo.getCountDeleted(), 0); + // jgibbs, hbarbossa, jbeckett, user1, user2, user3 assertEquals(syncInfo.getCountLinked(), getDefaultUsers() + getProcessedUsers()); assertEquals(syncInfo.getCountUnlinked(), 0); - assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + assertEquals(syncInfo.getCountUnmatchedAfter(), 5); assertEquals(syncInfo.getCountDeletedAfter(), 0); - assertEquals(syncInfo.getCountLinkedAfter(), 0); + assertEquals(syncInfo.getCountLinkedAfter(), getDefaultUsers() + getProcessedUsers()); assertEquals(syncInfo.getCountUnlinkedAfter(), 0); } @@ -87,14 +93,19 @@ protected void assertSynchronizationStatisticsActivation(Task taskAfter) { IterativeTaskInformationType infoType = taskAfter.getStoredOperationStats().getIterativeTaskInformation(); assertEquals(infoType.getTotalFailureCount(), 1); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnmatched(), 3); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountDeleted(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountLinked(), getDefaultUsers() + getProcessedUsers()); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnlinked(), 0); + SynchronizationInformationType syncInfo = taskAfter.getStoredOperationStats().getSynchronizationInformation(); + dumpSynchronizationInformation(syncInfo); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnmatchedAfter(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountDeleted(), 0); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountLinked(), getDefaultUsers() + getProcessedUsers()); - assertEquals(taskAfter.getStoredOperationStats().getSynchronizationInformation().getCountUnlinked(), 0); + assertEquals(syncInfo.getCountUnmatched(), 0); + assertEquals(syncInfo.getCountDeleted(), 0); + // jgibbs, hbarbossa, jbeckett, user1 (disabled-#1), user2 (disabled-#2), user3 (disabled-#3-fails) + assertEquals(syncInfo.getCountLinked(), getDefaultUsers() + getProcessedUsers()); + assertEquals(syncInfo.getCountUnlinked(), 0); + + assertEquals(syncInfo.getCountUnmatchedAfter(), 0); + assertEquals(syncInfo.getCountDeleted(), 0); + // jgibbs, hbarbossa, jbeckett, user1 (disabled-#1), user2 (disabled-#2), user3 (disabled-#3-fails) + assertEquals(syncInfo.getCountLinked(), getDefaultUsers() + getProcessedUsers()); + assertEquals(syncInfo.getCountUnlinked(), 0); } } diff --git a/testing/story/src/test/resources/thresholds/role-policy-rule-change-activation.xml b/testing/story/src/test/resources/thresholds/role-policy-rule-change-activation.xml index 7fe6fbba8e9..bd2c46eb00b 100644 --- a/testing/story/src/test/resources/thresholds/role-policy-rule-change-activation.xml +++ b/testing/story/src/test/resources/thresholds/role-policy-rule-change-activation.xml @@ -6,13 +6,13 @@ --> - Metarole stop on activation change (3) + Metarole stop on activation change (2) Change activation - add + modify activation/administrativeStatus diff --git a/testing/story/src/test/resources/thresholds/task-opendj-livesync-full.xml b/testing/story/src/test/resources/thresholds/task-opendj-livesync-full.xml index a1537f47380..3f7f61d7b7d 100644 --- a/testing/story/src/test/resources/thresholds/task-opendj-livesync-full.xml +++ b/testing/story/src/test/resources/thresholds/task-opendj-livesync-full.xml @@ -16,8 +16,7 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> - - LiveSync Simulate: Dummy + LiveSync Full: Dummy ri:inetOrgPerson diff --git a/testing/story/src/test/resources/thresholds/task-opendj-livesync-simulate.xml b/testing/story/src/test/resources/thresholds/task-opendj-livesync-simulate.xml index cbc7767d069..caa338d7ea1 100644 --- a/testing/story/src/test/resources/thresholds/task-opendj-livesync-simulate.xml +++ b/testing/story/src/test/resources/thresholds/task-opendj-livesync-simulate.xml @@ -16,7 +16,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> - LiveSync Simulate: Dummy diff --git a/testing/story/src/test/resources/thresholds/task-opendj-reconcile-full.xml b/testing/story/src/test/resources/thresholds/task-opendj-reconcile-full.xml index c088a160e48..c268250d1db 100644 --- a/testing/story/src/test/resources/thresholds/task-opendj-reconcile-full.xml +++ b/testing/story/src/test/resources/thresholds/task-opendj-reconcile-full.xml @@ -10,18 +10,17 @@ - Reconciliation Full: Dummy - ri:inetOrgPerson - account - default + ri:inetOrgPerson + account + default 20335c7c-838f-11e8-93a6-4b1dd0ab58e4 diff --git a/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate-execute.xml b/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate-execute.xml index 39718fc0d1c..bc1d23b51df 100644 --- a/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate-execute.xml +++ b/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate-execute.xml @@ -15,7 +15,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> - Reconciliation Simulate Execute: Dummy diff --git a/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate.xml b/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate.xml index d6dd490e607..448b4624025 100644 --- a/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate.xml +++ b/testing/story/src/test/resources/thresholds/task-opendj-reconcile-simulate.xml @@ -15,7 +15,6 @@ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"> - Reconciliation Simulate: Dummy From fb552deb69497400c0c0f5cf80af2359fe0eec89 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 09:48:33 +0100 Subject: [PATCH 08/55] checkstyle.xml: local variables must follow common conventions, fixed This is fixed for production code, testing code has still exception (checkstyle-suppresions.xml). Final local variables had THIS_STYLE, now reverted to thisStyle. --- config/checkstyle/checkstyle.xml | 6 +- .../dataModel/dot/DotRepositoryDataItem.java | 8 +- .../model/impl/lens/ChangeExecutor.java | 152 ++++++++---------- .../impl/sync/AsyncUpdateTaskHandler.java | 6 +- .../model/impl/sync/LiveSyncTaskHandler.java | 24 +-- .../ucf/impl/connid/Slf4jConnectorLogger.java | 18 +-- .../repo/sql/perf/OutputFormatter.java | 13 +- .../restriction/ReferenceRestriction.java | 37 ++--- .../test/AbstractIntegrationTest.java | 6 +- .../execution/LocalNodeManager.java | 20 +-- 10 files changed, 128 insertions(+), 162 deletions(-) diff --git a/config/checkstyle/checkstyle.xml b/config/checkstyle/checkstyle.xml index 5be0bc35a68..83664af8761 100644 --- a/config/checkstyle/checkstyle.xml +++ b/config/checkstyle/checkstyle.xml @@ -33,11 +33,7 @@ - - - - - + diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/dataModel/dot/DotRepositoryDataItem.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/dataModel/dot/DotRepositoryDataItem.java index 6bcad8ef899..3dc54e328cc 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/dataModel/dot/DotRepositoryDataItem.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/dataModel/dot/DotRepositoryDataItem.java @@ -25,7 +25,7 @@ public class DotRepositoryDataItem implements DotDataItem { private static final String COLOR_DEFAULT = "black"; private static final String COLOR_FILL = "grey92"; - RepositoryDataItem dataItem; + private RepositoryDataItem dataItem; public DotRepositoryDataItem(RepositoryDataItem dataItem) { this.dataItem = dataItem; @@ -40,10 +40,10 @@ public String getNodeName() { public String getNodeLabel() { String entity = StringUtils.removeEnd(dataItem.getTypeName().getLocalPart(), "Type"); String pathString = dataItem.getItemPath().toString(); - final String EXT = "extension/"; - if (pathString.startsWith(EXT)) { + final String ext = "extension/"; + if (pathString.startsWith(ext)) { entity += " extension"; - pathString = pathString.substring(EXT.length()); + pathString = pathString.substring(ext.length()); } return entity + " " + pathString; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ChangeExecutor.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ChangeExecutor.java index fceb0a811da..af362e16357 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ChangeExecutor.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/lens/ChangeExecutor.java @@ -13,21 +13,22 @@ import static com.evolveum.midpoint.prism.PrismContainerValue.asContainerables; import static com.evolveum.midpoint.schema.internals.InternalsConfig.consistencyChecks; +import java.util.Collection; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import javax.annotation.PostConstruct; +import javax.xml.bind.JAXBElement; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.apache.commons.lang.BooleanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + import com.evolveum.midpoint.common.Clock; import com.evolveum.midpoint.common.SynchronizationUtils; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.equivalence.EquivalenceStrategy; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.xnode.PrimitiveXNode; -import com.evolveum.midpoint.prism.xnode.XNodeFactory; -import com.evolveum.midpoint.repo.api.ConflictWatcher; -import com.evolveum.midpoint.repo.api.ModificationPrecondition; -import com.evolveum.midpoint.repo.api.PreconditionViolationException; -import com.evolveum.midpoint.repo.common.expression.Expression; -import com.evolveum.midpoint.repo.common.expression.ExpressionEvaluationContext; -import com.evolveum.midpoint.repo.common.expression.ExpressionFactory; -import com.evolveum.midpoint.repo.common.expression.ExpressionUtil; -import com.evolveum.midpoint.repo.common.expression.ExpressionVariables; import com.evolveum.midpoint.model.api.ModelAuthorizationAction; import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.api.ProgressInformation; @@ -40,17 +41,17 @@ import com.evolveum.midpoint.model.impl.util.ModelImplUtils; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.crypto.EncryptionException; +import com.evolveum.midpoint.prism.delta.*; +import com.evolveum.midpoint.prism.equivalence.EquivalenceStrategy; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.xnode.PrimitiveXNode; +import com.evolveum.midpoint.prism.xnode.XNodeFactory; import com.evolveum.midpoint.provisioning.api.ProvisioningOperationOptions; import com.evolveum.midpoint.provisioning.api.ProvisioningService; -import com.evolveum.midpoint.repo.api.RepoAddOptions; -import com.evolveum.midpoint.repo.api.RepositoryService; -import com.evolveum.midpoint.repo.api.VersionPrecondition; +import com.evolveum.midpoint.repo.api.*; +import com.evolveum.midpoint.repo.common.expression.*; import com.evolveum.midpoint.repo.common.util.RepoCommonUtils; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.ObjectDeltaOperation; -import com.evolveum.midpoint.schema.PointInTimeType; -import com.evolveum.midpoint.schema.ResourceShadowDiscriminator; -import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.*; import com.evolveum.midpoint.schema.constants.ExpressionConstants; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; @@ -81,21 +82,6 @@ import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; import com.evolveum.prism.xml.ns._public.types_3.RawType; -import org.apache.commons.lang.BooleanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import java.util.Collection; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -import javax.annotation.PostConstruct; -import javax.xml.bind.JAXBElement; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; - /** * @author semancik */ @@ -139,8 +125,8 @@ private void locateDefinitions() { // ObjectAlreadyExistsException handling (TODO specify more exactly) public boolean executeChanges(LensContext context, Task task, OperationResult parentResult) throws ObjectAlreadyExistsException, ObjectNotFoundException, - SchemaException, CommunicationException, ConfigurationException, - SecurityViolationException, ExpressionEvaluationException, PreconditionViolationException, PolicyViolationException { + SchemaException, CommunicationException, ConfigurationException, + SecurityViolationException, ExpressionEvaluationException, PreconditionViolationException, PolicyViolationException { OperationResult result = parentResult.createSubresult(OPERATION_EXECUTE); @@ -353,7 +339,6 @@ public boolean executeChanges(LensContext context, Tas ModelImplUtils.handleConnectorErrorCriticality(projCtx.getResource(), e, subResult); - } catch (ObjectAlreadyExistsException e) { // This exception is quite special. We have to decide how bad this really is. @@ -513,7 +498,7 @@ private void applyLastProvisioningTimestamp(LensContext accDelta, LensProjectionContext accCtx) { return (accDelta == null || accDelta.isEmpty()) - && (accCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.DELETE + && (accCtx.getSynchronizationPolicyDecision() == SynchronizationPolicyDecision.DELETE || accCtx.getSynchronizationIntent() == SynchronizationIntent.DELETE); } @@ -645,7 +630,7 @@ private void updateLinks(LensContext return; } LOGGER.error("Projection {} has null OID, this should not happen, context:\n{}", projCtx.toHumanReadableString(), projCtx.debugDump()); - throw new IllegalStateException("Projection "+projCtx.toHumanReadableString()+" has null OID, this should not happen"); + throw new IllegalStateException("Projection " + projCtx.toHumanReadableString() + " has null OID, this should not happen"); } if (linkShouldExist(projCtx, shadowAfterModification, result)) { @@ -892,14 +877,14 @@ private void updateSituationInShadow(Task task, Synchroni /** * @return Returns estimate of the object after modification. Or null if the object was deleted. - * NOTE: this is only partially implemented (only for shadow delete). + * NOTE: this is only partially implemented (only for shadow delete). */ private PrismObject executeDelta(ObjectDelta objectDelta, LensElementContext objectContext, LensContext context, ModelExecuteOptions options, ConflictResolutionType conflictResolution, ResourceType resource, Task task, OperationResult parentResult) - throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, - CommunicationException, ConfigurationException, SecurityViolationException, - PolicyViolationException, ExpressionEvaluationException, PreconditionViolationException { + throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, + CommunicationException, ConfigurationException, SecurityViolationException, + PolicyViolationException, ExpressionEvaluationException, PreconditionViolationException { if (objectDelta == null) { throw new IllegalArgumentException("Null change"); @@ -1056,7 +1041,7 @@ private ObjectDelta computeDeltaToExecute(ObjectDelta< } if (LOGGER.isTraceEnabled()) { LOGGER.trace("Computing delta to execute from delta:\n{}\nGiven these executed deltas:\n{}", - objectDelta.debugDump(1), LensObjectDeltaOperation.shorterDebugDump(objectContext.getExecutedDeltas(),1)); + objectDelta.debugDump(1), LensObjectDeltaOperation.shorterDebugDump(objectContext.getExecutedDeltas(), 1)); } List> executedDeltas = objectContext.getExecutedDeltas(); ObjectDelta diffDelta = computeDiffDelta(executedDeltas, objectDelta); @@ -1081,12 +1066,12 @@ private ObjectDelta computeDeltaToExecute(ObjectDelta< * and objectDelta is about to be executed; eliminates parts that have * already been done. It is meant as a kind of optimization (for MODIFY * deltas) and error avoidance (for ADD deltas). - * + *

* Explanation for ADD deltas: there are situations where an execution wave * is restarted - when unexpected AlreadyExistsException is reported from * provisioning. However, in such cases, duplicate ADD Focus deltas were * generated. So we (TEMPORARILY!) decided to filter them out here. - * + *

* Unfortunately, this mechanism is not well-defined, and seems to work more * "by accident" than "by design". It should be replaced with something more * serious. Perhaps by re-reading current focus state when repeating a wave? @@ -1095,12 +1080,11 @@ private ObjectDelta computeDeltaToExecute(ObjectDelta< * deltas (and as far as I know, that is the only place where this problem * should occur). Nevertheless, for historical and safety reasons I keep * also the processing in this method. - * + *

* Anyway, currently it treats only three cases: - * 1) if the objectDelta is present in the list of executed deltas - * 2) if the objectDelta is ADD, and another ADD delta is there (then the difference is computed) - * 3) if objectDelta is MODIFY or DELETE and previous delta was MODIFY - * + * 1) if the objectDelta is present in the list of executed deltas + * 2) if the objectDelta is ADD, and another ADD delta is there (then the difference is computed) + * 3) if objectDelta is MODIFY or DELETE and previous delta was MODIFY */ private ObjectDelta computeDiffDelta( List> executedDeltas, ObjectDelta objectDelta) { @@ -1119,7 +1103,7 @@ private ObjectDelta computeDiffDelta( } if (lastRelated.getExecutionResult().isSuccess() && lastRelated.containsDelta(objectDelta)) { return null; // case 1 - exact match found with SUCCESS result, - // let's skip the processing of our delta + // let's skip the processing of our delta } if (!objectDelta.isAdd()) { if (lastRelated.getObjectDelta().isDelete()) { @@ -1131,7 +1115,7 @@ private ObjectDelta computeDiffDelta( // determine if we got case 2 if (lastRelated.getObjectDelta().isDelete()) { return objectDelta; // we can (and should) apply the ADD delta as a - // whole, because the object was deleted + // whole, because the object was deleted } // let us treat the most simple case here - meaning we have existing ADD // delta and nothing more @@ -1185,7 +1169,7 @@ private ObjectDeltaOperation findLastRelatedDelta( } if (FocusType.class.isAssignableFrom(currentObjectClass)) { return currentOdo; // we suppose there is only one delta of - // Focus class + // Focus class } } return null; @@ -1340,7 +1324,6 @@ private PrismObject executeAddit securityEnforcer.authorize(ModelAuthorizationAction.ADD.getUrl(), AuthorizationPhaseType.EXECUTION, AuthorizationParameters.Builder.buildObjectAdd(objectToAdd), ownerResolver, task, result); - metadataManager.applyMetadataAdd(context, objectToAdd, clock.currentTimeXMLGregorianCalendar(), task, result); if (options == null) { @@ -1363,7 +1346,7 @@ private PrismObject executeAddit } else if (ObjectTypes.isManagedByProvisioning(objectTypeToAdd)) { ProvisioningOperationOptions provisioningOptions = getProvisioningOptions(context, options, - (PrismObject)objectContext.getObjectCurrent(), (ObjectDelta)change); + (PrismObject) objectContext.getObjectCurrent(), (ObjectDelta) change); oid = addProvisioningObject(objectToAdd, context, objectContext, provisioningOptions, resource, task, result); @@ -1397,7 +1380,6 @@ private PrismObject executeAddit } throw t; - } } @@ -1432,7 +1414,7 @@ private PrismObject executeDelet taskManager.deleteNode(oid, result); } else if (ObjectTypes.isClassManagedByProvisioning(objectTypeClass)) { ProvisioningOperationOptions provisioningOptions = getProvisioningOptions(context, options, - (PrismObject)objectContext.getObjectCurrent(), (ObjectDelta)change); + (PrismObject) objectContext.getObjectCurrent(), (ObjectDelta) change); try { objectAfterModification = deleteProvisioningObject(objectTypeClass, oid, context, objectContext, provisioningOptions, resource, task, result); @@ -1478,8 +1460,8 @@ private PrismObject executeDelet private void executeModification(ObjectDelta delta, LensContext context, LensElementContext objectContext, ModelExecuteOptions options, ConflictResolutionType conflictResolution, ResourceType resource, Task task, OperationResult result) - throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, CommunicationException, - ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, PreconditionViolationException { + throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException, CommunicationException, + ConfigurationException, SecurityViolationException, PolicyViolationException, ExpressionEvaluationException, PreconditionViolationException { Class objectTypeClass = delta.getObjectTypeClass(); // We need current object here. The current object is used to get data for id-only container delete deltas, @@ -1509,7 +1491,7 @@ private void executeModification(Ob throw new UnsupportedOperationException("NodeType is not modifiable using model interface"); } else if (ObjectTypes.isClassManagedByProvisioning(objectTypeClass)) { ProvisioningOperationOptions provisioningOptions = getProvisioningOptions(context, options, - (PrismObject)objectContext.getObjectCurrent(), (ObjectDelta)delta); + (PrismObject) objectContext.getObjectCurrent(), (ObjectDelta) delta); String oid = modifyProvisioningObject(objectTypeClass, delta.getOid(), delta.getModifications(), context, objectContext, provisioningOptions, resource, task, result); @@ -1566,8 +1548,8 @@ private String addTask(TaskType task, RepoAddOptions addOpt, OperationResult res private String addProvisioningObject(PrismObject object, LensContext context, LensElementContext objectContext, ProvisioningOperationOptions options, ResourceType resource, Task task, OperationResult result) throws ObjectNotFoundException, - ObjectAlreadyExistsException, SchemaException, CommunicationException, - ConfigurationException, SecurityViolationException, ExpressionEvaluationException, PolicyViolationException { + ObjectAlreadyExistsException, SchemaException, CommunicationException, + ConfigurationException, SecurityViolationException, ExpressionEvaluationException, PolicyViolationException { if (object.canRepresent(ShadowType.class)) { ShadowType shadow = (ShadowType) object.asObjectable(); @@ -1591,9 +1573,9 @@ private String addProvisioningObjec private PrismObject deleteProvisioningObject( Class objectTypeClass, String oid, LensContext context, LensElementContext objectContext, ProvisioningOperationOptions options, ResourceType resource, Task task, OperationResult result) - throws ObjectNotFoundException, ObjectAlreadyExistsException, SchemaException, - CommunicationException, ConfigurationException, SecurityViolationException, - ExpressionEvaluationException, PolicyViolationException { + throws ObjectNotFoundException, ObjectAlreadyExistsException, SchemaException, + CommunicationException, ConfigurationException, SecurityViolationException, + ExpressionEvaluationException, PolicyViolationException { PrismObject shadowToModify = null; OperationProvisioningScriptsType scripts = null; @@ -1621,8 +1603,8 @@ private String modifyProvisioningOb Class objectTypeClass, String oid, Collection modifications, LensContext context, LensElementContext objectContext, ProvisioningOperationOptions options, ResourceType resource, Task task, OperationResult result) throws ObjectNotFoundException, - CommunicationException, SchemaException, ConfigurationException, - SecurityViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException, PolicyViolationException { + CommunicationException, SchemaException, ConfigurationException, + SecurityViolationException, ExpressionEvaluationException, ObjectAlreadyExistsException, PolicyViolationException { PrismObject shadowToModify = null; OperationProvisioningScriptsType scripts = null; @@ -1655,8 +1637,8 @@ private String modifyProvisioningOb private OperationProvisioningScriptsType prepareScripts( PrismObject changedObject, LensContext context, LensElementContext objectContext, ProvisioningOperationTypeType operation, ResourceType resource, Task task, OperationResult result) - throws ObjectNotFoundException, SchemaException, CommunicationException, - ConfigurationException, SecurityViolationException, ExpressionEvaluationException { + throws ObjectNotFoundException, SchemaException, CommunicationException, + ConfigurationException, SecurityViolationException, ExpressionEvaluationException { if (resource == null) { LOGGER.warn("Resource does not exist. Skipping processing scripts."); @@ -1713,7 +1695,7 @@ private OperationProvisioningScriptsType evaluateScript(OperationProvisioningScr ExpressionVariables variables, ExpressionProfile expressionProfile, LensContext context, LensElementContext objectContext, Task task, OperationResult result) - throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { OperationProvisioningScriptsType outScripts = new OperationProvisioningScriptsType(); if (resourceScripts != null) { @@ -1740,7 +1722,7 @@ private OperationProvisioningScriptsType evaluateScript(OperationProvisioningScr } } // Let's do the most expensive evaluation last - if (!evaluateScriptCondition(script, variables, expressionProfile, task, result)){ + if (!evaluateScriptCondition(script, variables, expressionProfile, task, result)) { continue; } for (ProvisioningScriptArgumentType argument : script.getArgument()) { @@ -1773,21 +1755,21 @@ private boolean evaluateScriptCondition(OperationProvisioningScriptType script, private void evaluateScriptArgument(ProvisioningScriptArgumentType argument, ExpressionVariables variables, LensContext context, - LensElementContext objectContext, Task task, - OperationResult result) - throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, SecurityViolationException { + LensElementContext objectContext, Task task, OperationResult result) + throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, SecurityViolationException { - final QName FAKE_SCRIPT_ARGUMENT_NAME = new QName(SchemaConstants.NS_C, "arg"); + final QName fakeScriptArgumentName = new QName(SchemaConstants.NS_C, "arg"); PrismPropertyDefinition scriptArgumentDefinition = prismContext.definitionFactory().createPropertyDefinition( - FAKE_SCRIPT_ARGUMENT_NAME, DOMUtil.XSD_STRING); + fakeScriptArgumentName, DOMUtil.XSD_STRING); String shortDesc = "Provisioning script argument expression"; Expression, PrismPropertyDefinition> expression = expressionFactory .makeExpression(argument, scriptArgumentDefinition, MiscSchemaUtil.getExpressionProfile(), shortDesc, task, result); ExpressionEvaluationContext params = new ExpressionEvaluationContext(null, variables, shortDesc, task); - ExpressionEnvironment env = new ExpressionEnvironment<>(context, + ExpressionEnvironment env = new ExpressionEnvironment<>(context, objectContext instanceof LensProjectionContext ? (LensProjectionContext) objectContext : null, task, result); PrismValueDeltaSetTriple> outputTriple = ModelExpressionThreadLocalHolder .evaluateExpressionInContext(expression, params, env, result); @@ -1819,8 +1801,8 @@ private void evaluateScriptArgument(ProvisioningScriptArgumentType argument, private void executeReconciliationScript( LensProjectionContext projContext, LensContext context, BeforeAfterType order, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, - ExpressionEvaluationException, CommunicationException, ConfigurationException, - SecurityViolationException, ObjectAlreadyExistsException { + ExpressionEvaluationException, CommunicationException, ConfigurationException, + SecurityViolationException, ObjectAlreadyExistsException { if (!projContext.isDoReconciliation()) { return; @@ -1842,9 +1824,8 @@ private void executeReconciliationS private Object executeProvisioningScripts(LensContext context, LensProjectionContext projContext, OperationProvisioningScriptsType scripts, ProvisioningOperationTypeType operation, BeforeAfterType order, ExpressionProfile expressionProfile, Task task, OperationResult parentResult) - throws SchemaException, ObjectNotFoundException, - ExpressionEvaluationException, CommunicationException, ConfigurationException, - SecurityViolationException, ObjectAlreadyExistsException { + throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, SecurityViolationException, ObjectAlreadyExistsException { ResourceType resource = projContext.getResource(); if (resource == null) { @@ -1899,5 +1880,4 @@ private Object executeProvisioningS return scriptResult; } - } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/AsyncUpdateTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/AsyncUpdateTaskHandler.java index 40cd69eef19..4d0546155be 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/AsyncUpdateTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/AsyncUpdateTaskHandler.java @@ -64,9 +64,9 @@ public TaskRunResult run(RunningTask task, TaskPartitionDefinitionType partition task.setChannel(SchemaConstants.CHANGE_CHANNEL_ASYNC_UPDATE_URI); } - final String CTX = "Async Update"; + final String ctx = "Async Update"; - TargetInfo targetInfo = helper.getTargetInfo(LOGGER, task, opResult, runResult, CTX); + TargetInfo targetInfo = helper.getTargetInfo(LOGGER, task, opResult, runResult, ctx); if (targetInfo == null) { return runResult; } @@ -76,7 +76,7 @@ public TaskRunResult run(RunningTask task, TaskPartitionDefinitionType partition provisioningService.processAsynchronousUpdates(targetInfo.coords, task, opResult); } catch (RuntimeException | ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) { - helper.processException(LOGGER, e, opResult, runResult, partition, CTX); + helper.processException(LOGGER, e, opResult, runResult, partition, ctx); return runResult; } diff --git a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/LiveSyncTaskHandler.java b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/LiveSyncTaskHandler.java index 7edaf48350f..bf3b2e92c4e 100644 --- a/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/LiveSyncTaskHandler.java +++ b/model/model-impl/src/main/java/com/evolveum/midpoint/model/impl/sync/LiveSyncTaskHandler.java @@ -8,7 +8,6 @@ import javax.annotation.PostConstruct; -import com.evolveum.midpoint.prism.PrismContext; import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; @@ -21,25 +20,19 @@ import com.evolveum.midpoint.schema.result.OperationConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; -import com.evolveum.midpoint.task.api.RunningTask; -import com.evolveum.midpoint.task.api.StatisticsCollectionStrategy; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskCategory; -import com.evolveum.midpoint.task.api.TaskHandler; -import com.evolveum.midpoint.task.api.TaskManager; -import com.evolveum.midpoint.task.api.TaskRunResult; +import com.evolveum.midpoint.task.api.*; import com.evolveum.midpoint.task.api.TaskRunResult.TaskRunResultStatus; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskPartitionDefinitionType; + /** * The task handler for a live synchronization. - * - * This handler takes care of executing live synchronization "runs". It means that the handler "run" method will - * be called every few seconds. The responsibility is to scan for changes that happened since the last run. + *

+ * This handler takes care of executing live synchronization "runs". It means that the handler "run" method will + * be called every few seconds. The responsibility is to scan for changes that happened since the last run. * * @author Radovan Semancik - * */ @Component public class LiveSyncTaskHandler implements TaskHandler { @@ -48,7 +41,6 @@ public class LiveSyncTaskHandler implements TaskHandler { @Autowired private TaskManager taskManager; @Autowired private ProvisioningService provisioningService; - @Autowired private PrismContext prismContext; @Autowired private SyncTaskHelper helper; private static final Trace LOGGER = TraceManager.getTrace(LiveSyncTaskHandler.class); @@ -80,9 +72,9 @@ public TaskRunResult run(RunningTask task, TaskPartitionDefinitionType partition task.setChannel(SchemaConstants.CHANGE_CHANNEL_LIVE_SYNC_URI); } - final String CTX = "Live Sync"; + final String ctx = "Live Sync"; - TargetInfo targetInfo = helper.getTargetInfo(LOGGER, task, opResult, runResult, CTX); + TargetInfo targetInfo = helper.getTargetInfo(LOGGER, task, opResult, runResult, ctx); if (targetInfo == null) { return runResult; } @@ -96,7 +88,7 @@ public TaskRunResult run(RunningTask task, TaskPartitionDefinitionType partition ModelImplUtils.clearRequestee(task); changesProcessed = provisioningService.synchronize(targetInfo.coords, task, partition, opResult); } catch (Throwable t) { - helper.processException(LOGGER, t, opResult, runResult, partition, CTX); + helper.processException(LOGGER, t, opResult, runResult, partition, ctx); return runResult; } diff --git a/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/Slf4jConnectorLogger.java b/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/Slf4jConnectorLogger.java index be9de6dadc4..3554b8d9bf7 100644 --- a/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/Slf4jConnectorLogger.java +++ b/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/Slf4jConnectorLogger.java @@ -28,7 +28,7 @@ public class Slf4jConnectorLogger implements LogSpi { @Override public void log(Class clazz, String method, Level level, String message, Throwable ex) { - final Trace LOGGER = TraceManager.getTrace(clazz); + final Trace logger = TraceManager.getTrace(clazz); //Mark all messages from ICF as ICF Marker m = MarkerFactory.getMarker("ICF"); @@ -39,27 +39,27 @@ public void log(Class clazz, String method, Level level, String message, Thro // ERROR -> error if (Level.OK.equals(level)) { if (null == ex) { - LOGGER.trace(m, "method: {} msg:{}", method, message); + logger.trace(m, "method: {} msg:{}", method, message); } else { - LOGGER.trace(m, "method: {} msg:{}", new Object[] { method, message }, ex); + logger.trace(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } else if (Level.INFO.equals(level)) { if (null == ex) { - LOGGER.debug(m, "method: {} msg:{}", method, message); + logger.debug(m, "method: {} msg:{}", method, message); } else { - LOGGER.debug(m, "method: {} msg:{}", new Object[] { method, message }, ex); + logger.debug(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } else if (Level.WARN.equals(level)) { if (null == ex) { - LOGGER.warn(m, "method: {} msg:{}", method, message); + logger.warn(m, "method: {} msg:{}", method, message); } else { - LOGGER.warn(m, "method: {} msg:{}", new Object[] { method, message }, ex); + logger.warn(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } else if (Level.ERROR.equals(level)) { if (null == ex) { - LOGGER.error(m, "method: {} msg:{}", method, message); + logger.error(m, "method: {} msg:{}", method, message); } else { - LOGGER.error(m, "method: {} msg:{}", new Object[] { method, message }, ex); + logger.error(m, "method: {} msg:{}", new Object[] { method, message }, ex); } } } diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/perf/OutputFormatter.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/perf/OutputFormatter.java index 0c7a4127e09..7dee3d0e32c 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/perf/OutputFormatter.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/perf/OutputFormatter.java @@ -20,9 +20,6 @@ import java.util.List; import java.util.Map; -/** - * - */ class OutputFormatter { private static final Trace LOGGER = TraceManager.getTrace(OutputFormatter.class); @@ -49,16 +46,16 @@ static void writeStatisticsToFile(String file, List finishedOpe static String getFormattedStatistics(List finishedOperations, Map outstandingOperations) { StatEntry all = new StatEntry(); StatEntry unfinished = new StatEntry(); - final int MAX_ATTEMPTS = SqlBaseService.LOCKING_MAX_RETRIES + 1; - StatEntry[] perAttempts = new StatEntry[MAX_ATTEMPTS]; + final int maxAttempts = SqlBaseService.LOCKING_MAX_RETRIES + 1; + StatEntry[] perAttempts = new StatEntry[maxAttempts]; - for (int i = 0; i < MAX_ATTEMPTS; i++) { + for (int i = 0; i < maxAttempts; i++) { perAttempts[i] = new StatEntry(); } for (OperationRecord operation : finishedOperations) { all.process(operation); - if (operation.getAttempts() >= 1 && operation.getAttempts() <= MAX_ATTEMPTS) { + if (operation.getAttempts() >= 1 && operation.getAttempts() <= maxAttempts) { perAttempts[operation.getAttempts() -1].process(operation); } else if (operation.getAttempts() < 0) { unfinished.process(operation); @@ -67,7 +64,7 @@ static String getFormattedStatistics(List finishedOperations, M StringBuilder retval = new StringBuilder(); retval.append("Overall: ").append(all.dump()).append("\n"); - for (int i = 0; i < MAX_ATTEMPTS; i++) { + for (int i = 0; i < maxAttempts; i++) { retval.append(i + 1).append(" attempt(s): ").append(perAttempts[i].dump()).append("\n"); } retval.append("Unfinished: ").append(unfinished.dump()).append("\n"); diff --git a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/restriction/ReferenceRestriction.java b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/restriction/ReferenceRestriction.java index ffa3d1c0ac2..24701a6553d 100644 --- a/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/restriction/ReferenceRestriction.java +++ b/repo/repo-sql-impl/src/main/java/com/evolveum/midpoint/repo/sql/query2/restriction/ReferenceRestriction.java @@ -7,6 +7,13 @@ package com.evolveum.midpoint.repo.sql.query2.restriction; +import java.util.*; +import java.util.stream.Collectors; +import javax.xml.namespace.QName; + +import org.apache.commons.collections4.CollectionUtils; +import org.jetbrains.annotations.NotNull; + import com.evolveum.midpoint.prism.PrismConstants; import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.query.RefFilter; @@ -16,8 +23,8 @@ import com.evolveum.midpoint.repo.sql.query2.InterpretationContext; import com.evolveum.midpoint.repo.sql.query2.definition.JpaAnyReferenceDefinition; import com.evolveum.midpoint.repo.sql.query2.definition.JpaEntityDefinition; -import com.evolveum.midpoint.repo.sql.query2.definition.JpaReferenceDefinition; import com.evolveum.midpoint.repo.sql.query2.definition.JpaLinkDefinition; +import com.evolveum.midpoint.repo.sql.query2.definition.JpaReferenceDefinition; import com.evolveum.midpoint.repo.sql.query2.hqm.RootHibernateQuery; import com.evolveum.midpoint.repo.sql.query2.hqm.condition.AndCondition; import com.evolveum.midpoint.repo.sql.query2.hqm.condition.Condition; @@ -29,12 +36,6 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; -import org.apache.commons.collections4.CollectionUtils; -import org.jetbrains.annotations.NotNull; - -import javax.xml.namespace.QName; -import java.util.*; -import java.util.stream.Collectors; /** * @author lazyman @@ -47,7 +48,7 @@ public class ReferenceRestriction extends ItemValueRestriction { @NotNull private final JpaLinkDefinition linkDefinition; public ReferenceRestriction(InterpretationContext context, RefFilter filter, JpaEntityDefinition baseEntityDefinition, - Restriction parent, @NotNull JpaLinkDefinition linkDefinition) { + Restriction parent, @NotNull JpaLinkDefinition linkDefinition) { super(context, filter, baseEntityDefinition, parent); this.linkDefinition = linkDefinition; } @@ -120,28 +121,28 @@ private Condition createRefCondition(RootHibernateQuery hibernateQuery, Collection oids, QName relation, QName targetType) { String hqlPath = hqlDataInstance.getHqlPath(); - final String TARGET_OID_HQL_PROPERTY, RELATION_HQL_PROPERTY, TARGET_TYPE_HQL_PROPERTY; + final String targetOidHqlProperty, relationHqlProperty, targetTypeHqlProperty; if (linkDefinition.getTargetDefinition() instanceof JpaAnyReferenceDefinition) { - TARGET_OID_HQL_PROPERTY = ROExtReference.F_TARGET_OID; - RELATION_HQL_PROPERTY = ROExtReference.F_RELATION; - TARGET_TYPE_HQL_PROPERTY = ROExtReference.F_TARGET_TYPE; + targetOidHqlProperty = ROExtReference.F_TARGET_OID; + relationHqlProperty = ROExtReference.F_RELATION; + targetTypeHqlProperty = ROExtReference.F_TARGET_TYPE; } else { - TARGET_OID_HQL_PROPERTY = RObjectReference.F_TARGET_OID; - RELATION_HQL_PROPERTY = RObjectReference.F_RELATION; - TARGET_TYPE_HQL_PROPERTY = RObjectReference.F_TARGET_TYPE; + targetOidHqlProperty = RObjectReference.F_TARGET_OID; + relationHqlProperty = RObjectReference.F_RELATION; + targetTypeHqlProperty = RObjectReference.F_TARGET_TYPE; } AndCondition conjunction = hibernateQuery.createAnd(); if (CollectionUtils.isNotEmpty(oids)) { - conjunction.add(hibernateQuery.createEqOrInOrNull(hqlDataInstance.getHqlPath() + "." + TARGET_OID_HQL_PROPERTY, oids)); + conjunction.add(hibernateQuery.createEqOrInOrNull(hqlDataInstance.getHqlPath() + "." + targetOidHqlProperty, oids)); } List relationsToTest = getRelationsToTest(relation, getContext()); if (!relationsToTest.isEmpty()) { - conjunction.add(hibernateQuery.createEqOrInOrNull(hqlPath + "." + RELATION_HQL_PROPERTY, relationsToTest)); + conjunction.add(hibernateQuery.createEqOrInOrNull(hqlPath + "." + relationHqlProperty, relationsToTest)); } if (targetType != null) { - conjunction.add(handleEqInOrNull(hibernateQuery, hqlPath + "." + TARGET_TYPE_HQL_PROPERTY, + conjunction.add(handleEqInOrNull(hibernateQuery, hqlPath + "." + targetTypeHqlProperty, ClassMapper.getHQLTypeForQName(targetType))); } return conjunction; diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index c5e80c74f81..7222cc172ae 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -740,7 +740,7 @@ protected void assumeConflictResolutionAction(ConflictResolutionActionType actio SystemConfigurationType systemConfiguration = getSystemConfiguration(); List current = new ArrayList<>(); List currentForTasks = new ArrayList<>(); - final ConflictResolutionActionType ACTION_FOR_TASKS = ConflictResolutionActionType.NONE; + final ConflictResolutionActionType actionForTasks = ConflictResolutionActionType.NONE; for (ObjectPolicyConfigurationType c : systemConfiguration.getDefaultObjectPolicyConfiguration()) { if (c.getType() == null && c.getSubtype() == null && c.getConflictResolution() != null) { current.add(c); @@ -760,11 +760,11 @@ protected void assumeConflictResolutionAction(ConflictResolutionActionType actio .deleteRealValues(current) .asItemDelta()); } - if (currentForTasks.size() != 1 || currentForTasks.get(0).getConflictResolution().getAction() != ACTION_FOR_TASKS) { + if (currentForTasks.size() != 1 || currentForTasks.get(0).getConflictResolution().getAction() != actionForTasks) { ObjectPolicyConfigurationType newPolicyForTasks = new ObjectPolicyConfigurationType(prismContext) .type(TaskType.COMPLEX_TYPE) .beginConflictResolution() - .action(ACTION_FOR_TASKS) + .action(actionForTasks) .end(); itemDeltas.add(prismContext.deltaFor(SystemConfigurationType.class) .item(SystemConfigurationType.F_DEFAULT_OBJECT_POLICY_CONFIGURATION) diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java index 028f78ebc4b..768b0fc46c7 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java @@ -76,22 +76,22 @@ void initializeScheduler() throws TaskManagerInitializationException { createQuartzDbSchema(configuration); - final String MY_DS = "myDS"; - quartzProperties.put("org.quartz.jobStore.dataSource", MY_DS); + final String myDs = "myDS"; + quartzProperties.put("org.quartz.jobStore.dataSource", myDs); if (configuration.isUseRepositoryConnectionProvider()) { DataSourceFactory dataSourceFactory = (DataSourceFactory) taskManager.getBeanFactory().getBean("dataSourceFactory"); int index = (int) (Math.random() * Integer.MAX_VALUE); RepositoryConnectionProvider.DATA_SOURCES.put(index, dataSourceFactory.getDataSource()); - quartzProperties.put("org.quartz.dataSource."+MY_DS+".connectionProvider.class", RepositoryConnectionProvider.class.getName()); - quartzProperties.put("org.quartz.dataSource."+MY_DS+".dataSourceIndex", String.valueOf(index)); + quartzProperties.put("org.quartz.dataSource."+myDs+".connectionProvider.class", RepositoryConnectionProvider.class.getName()); + quartzProperties.put("org.quartz.dataSource."+myDs+".dataSourceIndex", String.valueOf(index)); } else if (configuration.getDataSource() != null) { - quartzProperties.put("org.quartz.dataSource."+MY_DS+".jndiURL", configuration.getDataSource()); + quartzProperties.put("org.quartz.dataSource."+myDs+".jndiURL", configuration.getDataSource()); } else { - quartzProperties.put("org.quartz.dataSource."+MY_DS+".provider", "hikaricp"); - quartzProperties.put("org.quartz.dataSource."+MY_DS+".driver", configuration.getJdbcDriver()); - quartzProperties.put("org.quartz.dataSource."+MY_DS+".URL", configuration.getJdbcUrl()); - quartzProperties.put("org.quartz.dataSource."+MY_DS+".user", configuration.getJdbcUser()); - quartzProperties.put("org.quartz.dataSource."+MY_DS+".password", configuration.getJdbcPassword()); + quartzProperties.put("org.quartz.dataSource."+myDs+".provider", "hikaricp"); + quartzProperties.put("org.quartz.dataSource."+myDs+".driver", configuration.getJdbcDriver()); + quartzProperties.put("org.quartz.dataSource."+myDs+".URL", configuration.getJdbcUrl()); + quartzProperties.put("org.quartz.dataSource."+myDs+".user", configuration.getJdbcUser()); + quartzProperties.put("org.quartz.dataSource."+myDs+".password", configuration.getJdbcPassword()); } quartzProperties.put("org.quartz.jobStore.isClustered", configuration.isClustered() ? "true" : "false"); From 7f7b2fef20fd0e48d8284fe53a27a9c9776b2cb8 Mon Sep 17 00:00:00 2001 From: Tony Tkacik Date: Fri, 6 Mar 2020 09:49:01 +0100 Subject: [PATCH 09/55] UniformItemPath: Make impl package visible Signed-off-by: Tony Tkacik --- .../midpoint/prism/path/UniformItemPath.java | 30 +++++++++++++++++-- .../prism/path/UniformItemPathImpl.java | 22 ++++---------- .../midpoint/prism/impl/PrismContextImpl.java | 11 ++++--- .../prism/impl/marshaller/ItemPathHolder.java | 11 ++++--- .../com/evolveum/midpoint/prism/TestPath.java | 4 +-- .../model/intest/gensync/TestEditSchema.java | 4 +-- 6 files changed, 47 insertions(+), 35 deletions(-) diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java index cc2776e7771..7e25e30f375 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPath.java @@ -14,14 +14,14 @@ import java.util.List; import java.util.Map; +import javax.xml.namespace.QName; + /** * @author semancik * */ public interface UniformItemPath extends Serializable, Cloneable, ShortDumpable, ItemPath { - UniformItemPath EMPTY_PATH = UniformItemPathImpl.EMPTY_PATH; - @NotNull List getSegments(); @@ -95,4 +95,30 @@ default UniformItemPath rest() { void setNamespaceMap(Map namespaceMap); Map getNamespaceMap(); + + static UniformItemPath empty() { + return UniformItemPathImpl.EMPTY_PATH; + } + + static UniformItemPath create(Object... segments) { + return UniformItemPathImpl.create(segments); + } + + static @NotNull UniformItemPath from(ItemPath path) { + return UniformItemPathImpl.fromItemPath(path); + } + + static ItemPathSegment createSegment(QName qname, boolean variable) { + if (ParentPathSegment.QNAME.equals(qname)) { + return new ParentPathSegment(); + } else if (ObjectReferencePathSegment.QNAME.equals(qname)) { + return new ObjectReferencePathSegment(); + } else if (IdentifierPathSegment.QNAME.equals(qname)) { + return new IdentifierPathSegment(); + } else if (variable) { + return new VariableItemPathSegment(qname); + } else { + return new NameItemPathSegment(qname); + } + } } diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java index 93cb90c7943..a31d1102210 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/path/UniformItemPathImpl.java @@ -18,7 +18,7 @@ * @author semancik * */ -public class UniformItemPathImpl implements UniformItemPath { +class UniformItemPathImpl implements UniformItemPath { public static final UniformItemPathImpl EMPTY_PATH = UniformItemPathImpl.createEmpty(); @@ -42,20 +42,6 @@ public static UniformItemPathImpl fromItemPath(ItemPath itemPath) { } } - public static ItemPathSegment createSegment(QName qname, boolean variable) { - if (ParentPathSegment.QNAME.equals(qname)) { - return new ParentPathSegment(); - } else if (ObjectReferencePathSegment.QNAME.equals(qname)) { - return new ObjectReferencePathSegment(); - } else if (IdentifierPathSegment.QNAME.equals(qname)) { - return new IdentifierPathSegment(); - } else if (variable) { - return new VariableItemPathSegment(qname); - } else { - return new NameItemPathSegment(qname); - } - } - public void setNamespaceMap(Map namespaceMap) { this.namespaceMap = namespaceMap; } @@ -216,7 +202,7 @@ private void add(Object object) { } private void add(QName qname) { - this.segments.add(createSegment(qname, false)); + this.segments.add(UniformItemPath.createSegment(qname, false)); } private void add(ItemPathSegment segment) { @@ -426,4 +412,8 @@ public String toString() { shortDump(sb); return sb.toString(); } + + static UniformItemPath create(Object... segments) { + return new UniformItemPathImpl(segments); + } } diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java index ef13edaa38f..04978714f13 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/PrismContextImpl.java @@ -16,7 +16,6 @@ import com.evolveum.midpoint.prism.impl.crypto.KeyStoreBasedProtectorImpl; import com.evolveum.midpoint.prism.impl.marshaller.*; import com.evolveum.midpoint.prism.impl.path.CanonicalItemPathImpl; -import com.evolveum.midpoint.prism.path.UniformItemPathImpl; import com.evolveum.midpoint.prism.impl.schema.SchemaDefinitionFactory; import com.evolveum.midpoint.prism.impl.schema.SchemaFactoryImpl; import com.evolveum.midpoint.prism.impl.schema.SchemaRegistryImpl; @@ -563,12 +562,12 @@ public ParsingContext createParsingContextForCompatibilityMode() { @Override public UniformItemPath emptyPath() { - return UniformItemPathImpl.EMPTY_PATH; + return UniformItemPath.empty(); } @Override public UniformItemPath path(Object... namesOrIdsOrSegments) { - return new UniformItemPathImpl(namesOrIdsOrSegments); + return UniformItemPath.create(namesOrIdsOrSegments); } @Override @@ -601,17 +600,17 @@ public KeyStoreBasedProtector createProtector(KeyStoreBasedProtectorBuilder buil @NotNull @Override public UniformItemPath toUniformPath(ItemPath path) { - return UniformItemPathImpl.fromItemPath(path); + return UniformItemPath.from(path); } @Override public UniformItemPath toUniformPathKeepNull(ItemPath path) { - return path != null ? UniformItemPathImpl.fromItemPath(path) : null; + return path != null ? UniformItemPath.from(path) : null; } @Override public UniformItemPath toUniformPath(ItemPathType path) { - return UniformItemPathImpl.fromItemPath(path.getItemPath()); + return UniformItemPath.from(path.getItemPath()); } @Override diff --git a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java index 669b27fc363..d39c5cded6a 100644 --- a/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java +++ b/infra/prism-impl/src/main/java/com/evolveum/midpoint/prism/impl/marshaller/ItemPathHolder.java @@ -8,7 +8,6 @@ package com.evolveum.midpoint.prism.impl.marshaller; import com.evolveum.midpoint.prism.PrismConstants; -import com.evolveum.midpoint.prism.path.UniformItemPathImpl; import com.evolveum.midpoint.prism.path.*; import com.evolveum.midpoint.prism.impl.xml.GlobalDynamicNamespacePrefixMapper; import com.evolveum.midpoint.util.DOMUtil; @@ -218,11 +217,11 @@ private String findNamespace(String prefix, Node domNode, Map na //region Serializing public static String serializeWithDeclarations(@NotNull ItemPath itemPath) { - return new ItemPathHolder(UniformItemPathImpl.fromItemPath(itemPath)).getXPathWithDeclarations(); + return new ItemPathHolder(UniformItemPath.from(itemPath)).getXPathWithDeclarations(); } public static String serializeWithForcedDeclarations(@NotNull ItemPath itemPath) { - return new ItemPathHolder(UniformItemPathImpl.fromItemPath(itemPath), true).getXPathWithDeclarations(); + return new ItemPathHolder(UniformItemPath.from(itemPath), true).getXPathWithDeclarations(); } private ItemPathHolder(@NotNull UniformItemPath itemPath) { @@ -398,7 +397,7 @@ public Map getNamespaceMap() { } public static Element serializeToElement(ItemPath path, QName elementQName, Document document) { - return new ItemPathHolder(UniformItemPathImpl.fromItemPath(path)).toElement(elementQName, document); + return new ItemPathHolder(UniformItemPath.from(path)).toElement(elementQName, document); } public Element toElement(QName elementQName, Document document) { @@ -443,10 +442,10 @@ public UniformItemPath toItemPath() { } else { QName qName = segment.getQName(); boolean variable = segment.isVariable(); - segments.add(UniformItemPathImpl.createSegment(qName, variable)); + segments.add(UniformItemPath.createSegment(qName, variable)); } } - UniformItemPath path = new UniformItemPathImpl(segments); + UniformItemPath path = UniformItemPath.create(segments); path.setNamespaceMap(explicitNamespaceDeclarations); return path; } diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java index 25964e0101c..c2c5128c8e9 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/TestPath.java @@ -40,8 +40,8 @@ public class TestPath extends AbstractPrismTest { */ @Test public void testEmptyPath() { - System.out.println("UniformItemPath.EMPTY_PATH = " + UniformItemPath.EMPTY_PATH); - System.out.println("UniformItemPathImpl.EMPTY_PATH = " + UniformItemPathImpl.EMPTY_PATH); + System.out.println("UniformItemPath.empty() = " + UniformItemPath.empty()); + assertNotNull(UniformItemPath.empty()); } @Test diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java index d32f6ea192b..79096ca8c82 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestEditSchema.java @@ -21,7 +21,6 @@ import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.path.UniformItemPath; -import com.evolveum.midpoint.prism.path.UniformItemPathImpl; import com.evolveum.midpoint.schema.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @@ -1696,7 +1695,6 @@ public void testEmptyPath() { * UniformItemPath.EMPTY_PATH = * UniformItemPathImpl.EMPTY_PATH = */ - System.out.println("UniformItemPath.EMPTY_PATH = " + UniformItemPath.EMPTY_PATH); - System.out.println("UniformItemPathImpl.EMPTY_PATH = " + UniformItemPathImpl.EMPTY_PATH); + System.out.println("UniformItemPath.EMPTY_PATH = " + UniformItemPath.empty()); } } From d46a6071adab5363dc246af422a4db72fc4b74a3 Mon Sep 17 00:00:00 2001 From: kate Date: Fri, 6 Mar 2020 09:59:15 +0100 Subject: [PATCH 10/55] MID-5958 localization for case summary panel --- .../gui/api/util/WebComponentUtil.java | 2 +- .../page/admin/cases/CaseSummaryPanel.java | 28 ++++++++++++++----- 2 files changed, 22 insertions(+), 8 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java index 995f3ae9d3e..cc0e6b81d06 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java @@ -1399,7 +1399,7 @@ public static String getDisplayNameOrName(PrismObject object, boolean translate, } String displayName = getDisplayName(object, translate, localizationService); - return displayName != null ? displayName : getName(object, translate, localizationService); + return StringUtils.isNotEmpty(displayName) ? displayName : getName(object, translate, localizationService); } public static String getDisplayNameOrName(ObjectReferenceType ref) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/cases/CaseSummaryPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/cases/CaseSummaryPanel.java index b049b69c974..3f648dad655 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/cases/CaseSummaryPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/cases/CaseSummaryPanel.java @@ -7,9 +7,14 @@ package com.evolveum.midpoint.web.page.admin.cases; import com.evolveum.midpoint.gui.api.GuiStyleConstants; +import com.evolveum.midpoint.gui.api.model.LoadableModel; import com.evolveum.midpoint.gui.api.util.ModelServiceLocator; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.CaseTypeUtil; +import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.web.component.ObjectSummaryPanel; import com.evolveum.midpoint.web.component.util.SummaryTag; import com.evolveum.midpoint.web.component.util.VisibleBehaviour; @@ -39,13 +44,22 @@ public CaseSummaryPanel(String id, Class type, IModel model, ModelServ @Override protected IModel getTitleModel() { - ObjectReferenceType parentRef = getModelObject().getParentRef(); - if (parentRef != null && StringUtils.isNotEmpty(parentRef.getOid())) { - return createStringResource("CaseSummaryPanel.parentCase", - WebComponentUtil.getDisplayNameOrName(getModelObject().getParentRef(), getPageBase(), OPERATION_LOAD_PARENT_CASE_DISPLAY_NAME, true)); - } else { - return null; - } + return new LoadableModel(){ + @Override + public String load(){ + ObjectReferenceType parentRef = getModelObject().getParentRef(); + if (parentRef != null && StringUtils.isNotEmpty(parentRef.getOid())) { + Task task = getPageBase().createSimpleTask(OPERATION_LOAD_PARENT_CASE_DISPLAY_NAME); + OperationResult result = new OperationResult(OPERATION_LOAD_PARENT_CASE_DISPLAY_NAME); + PrismObject parentCaseObj = WebModelServiceUtils.loadObject(CaseType.class, parentRef.getOid(), getPageBase(), + task, result); + return createStringResource("CaseSummaryPanel.parentCase", + WebComponentUtil.getDisplayNameOrName(parentCaseObj)).getString(); + } else { + return null; + } + } + }; } @Override From c0266ebfd6a9c8e5eeeba1b25383de9aba5e7a3a Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 11:00:56 +0100 Subject: [PATCH 11/55] ContainerableListPanel.java: typo + todo about suspicious exceptions --- .../midpoint/gui/api/component/ContainerableListPanel.java | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java index 53ad436b64a..cba7c8f6c44 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/ContainerableListPanel.java @@ -7,11 +7,8 @@ package com.evolveum.midpoint.gui.api.component; import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; -import com.evolveum.midpoint.model.api.ModelAuthorizationAction; import com.evolveum.midpoint.prism.Containerable; -import com.evolveum.midpoint.prism.PrismConstants; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectPaging; import com.evolveum.midpoint.prism.query.ObjectQuery; @@ -126,6 +123,7 @@ protected void saveProviderPaging(ObjectQuery query, ObjectPaging paging) { @Override public ObjectQuery getQuery() { try { + // TODO this seems to throw now checked exception (see unused throws lower) return createQuery(); } catch (SchemaException | ObjectNotFoundException | ExpressionEvaluationException | CommunicationException | ConfigurationException | SecurityViolationException e) { @@ -141,7 +139,7 @@ public ObjectQuery getQuery() { protected abstract Class getType(); protected void setDefaultSorting(ContainerListDataProvider provider){ - //should be overridded if needed + //should be overridden if needed } public long getItemsPerPage() { From b07120189d4e2db74d2dc8ef284d61c1a4a93f5e Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 12:38:23 +0100 Subject: [PATCH 12/55] test classes: another batch of TEST_NAME removal, reformat, cleanup --- .../AbstractInternalModelIntegrationTest.java | 14 +- .../model/impl/lens/TestReconScript.java | 10 +- .../TestCorrelationConfirmationEvaluator.java | 4 +- .../impl/sync/TestSynchronizationService.java | 2 +- .../midpoint/model/intest/TestActivation.java | 345 ++++-------- .../midpoint/model/intest/TestCaseIgnore.java | 59 +- .../model/intest/TestConnectorDummyFake.java | 106 +--- .../model/intest/TestConsistencySimple.java | 37 +- .../midpoint/model/intest/TestDeputy.java | 148 +---- .../model/intest/TestEntitlements.java | 239 ++------ .../midpoint/model/intest/TestInbounds.java | 96 +--- .../midpoint/model/intest/TestIntent.java | 17 - .../midpoint/model/intest/TestIteration.java | 328 +++-------- .../midpoint/model/intest/TestLifecycle.java | 41 +- .../midpoint/model/intest/TestMerge.java | 38 +- .../model/intest/TestModelCrudService.java | 48 +- .../intest/TestModelServiceContract.java | 354 ++++-------- .../model/intest/TestModelVisualization.java | 16 +- .../model/intest/TestNotifications.java | 67 +-- .../model/intest/TestPreviewChanges.java | 301 ++++------ .../model/intest/TestRaceConditions.java | 11 +- .../model/intest/TestSchemalessResource.java | 20 +- .../model/intest/TestScriptHooks.java | 48 +- .../model/intest/TestTolerantAttributes.java | 268 +++++---- .../model/intest/TestUserTemplate.java | 523 +++++++++--------- .../intest/TestUserTemplateWithRanges.java | 118 ++-- .../impl/dummy/TestDummyConsistency.java | 53 +- .../test/AbstractIntegrationTest.java | 2 +- 28 files changed, 1089 insertions(+), 2224 deletions(-) diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java index 83a0b495dce..56edcf10e4e 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/AbstractInternalModelIntegrationTest.java @@ -7,32 +7,26 @@ package com.evolveum.midpoint.model.impl; import java.io.File; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.test.TestResource; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.midpoint.model.impl.util.mock.MockClockworkHook; -import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.internals.InternalsConfig; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; +import com.evolveum.midpoint.test.TestResource; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author semancik - * */ @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class AbstractInternalModelIntegrationTest extends AbstractModelImplementationIntegrationTest { @@ -66,7 +60,7 @@ public class AbstractInternalModelIntegrationTest extends AbstractModelImplement protected static final String USER_ELAINE_USERNAME = "elaine"; // Largo does not have a full name set, employeeType=PIRATE - protected static final File USER_LARGO_FILE = new File(COMMON_DIR, "user-largo.xml"); + protected static final File USER_LARGO_FILE = new File(COMMON_DIR, "user-largo.xml"); protected static final String USER_LARGO_OID = "c0c010c0-d34d-b33f-f00d-111111111118"; public static final File ROLE_SUPERUSER_FILE = new File(COMMON_DIR, "role-superuser.xml"); @@ -113,8 +107,6 @@ public class AbstractInternalModelIntegrationTest extends AbstractModelImplement protected static final String MOCK_CLOCKWORK_HOOK_URL = MidPointConstants.NS_MIDPOINT_TEST_PREFIX + "/mockClockworkHook"; - protected static final Trace LOGGER = TraceManager.getTrace(AbstractModelIntegrationTest.class); - protected PrismObject userAdministrator; protected UserType userTypeJack; @@ -126,7 +118,7 @@ public class AbstractInternalModelIntegrationTest extends AbstractModelImplement @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); + logger.trace("initSystem"); super.initSystem(initTask, initResult); // We want logging config from logback-test.xml and not from system config object (unless suppressed) diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java index 78e2e892d98..e7bca1e3126 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestReconScript.java @@ -70,7 +70,7 @@ public void text001testReconcileScriptsWhenProvisioning() throws Exception { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + logger.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); if (!idPath.contains(userName)) { AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } @@ -97,7 +97,7 @@ public void test002testReconcileScriptsWhenReconciling() throws Exception { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + logger.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); if (!idPath.contains(userName)) { AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } @@ -110,9 +110,7 @@ public void test002testReconcileScriptsWhenReconciling() throws Exception { @Test public void test003testReconcileScriptsAddUserAction() throws Exception { - final String TEST_NAME = "test003testReconcileScriptsAddUserAction"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult parentResult = createOperationResult(); ShadowType shadow = parseObjectType(new File(ACCOUNT_BEFORE_SCRIPT_FILENAME), ShadowType.class); @@ -140,7 +138,7 @@ public void test003testReconcileScriptsAddUserAction() throws Exception { String userName = (String) script.getParams().get("midpoint_usercn"); String idPath = (String) script.getParams().get("midpoint_idpath"); String tempPath = (String) script.getParams().get("midpoint_temppath"); - LOGGER.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); + logger.trace("userName {} idPath {} tempPath {}", userName, idPath, tempPath); if (!idPath.contains(userName)) { AssertJUnit.fail("Expected that idPath will contain userName [idPath: " + idPath + ", userName " + userName + "]"); } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java index 25b0eafa828..a36a2e85bfc 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestCorrelationConfirmationEvaluator.java @@ -161,7 +161,7 @@ public void test004CorrelationMatchCaseInsensitive() throws Exception { AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex) { - LOGGER.error("exception occured: {}", ex.getMessage(), ex); + logger.error("exception occured: {}", ex.getMessage(), ex); throw ex; } } @@ -185,7 +185,7 @@ public void test005CorrelationMatchCaseInsensitive() throws Exception { AssertJUnit.assertTrue(matchedUsers); } catch (Exception ex) { - LOGGER.error("exception occured: {}", ex.getMessage(), ex); + logger.error("exception occured: {}", ex.getMessage(), ex); throw ex; } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java index 65bcd510f44..117cfbc3db9 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/sync/TestSynchronizationService.java @@ -76,7 +76,7 @@ public class TestSynchronizationService extends AbstractInternalModelIntegration @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { - LOGGER.trace("initSystem"); + logger.trace("initSystem"); super.initSystem(initTask, initResult); initDummyResourcePirate(RESOURCE_DUMMY_LIMITED_NAME, diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java index 04af15e9c13..893937ae425 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestActivation.java @@ -6,42 +6,32 @@ */ package com.evolveum.midpoint.model.intest; +import static org.testng.AssertJUnit.*; + import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_ACTIVATION_ENABLE_TIMESTAMP; import static com.evolveum.midpoint.schema.util.ObjectTypeUtil.cast; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.Date; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.icf.dummy.resource.DummyObjectClass; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; - -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.test.TestResource; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; -import com.evolveum.icf.dummy.resource.ConflictException; -import com.evolveum.icf.dummy.resource.DummyAccount; -import com.evolveum.icf.dummy.resource.DummyResource; -import com.evolveum.icf.dummy.resource.SchemaViolationException; -import com.evolveum.midpoint.model.intest.sync.AbstractSynchronizationStoryTest; +import com.evolveum.icf.dummy.resource.*; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.intest.sync.TestValidityRecomputeTask; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; @@ -50,33 +40,20 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; +import com.evolveum.midpoint.test.TestResource; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.LockoutStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ServiceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TimeIntervalStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * * @see TestValidityRecomputeTask */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestActivation extends AbstractInitializedModelIntegrationTest { @@ -169,10 +146,8 @@ public void test050CheckJackEnabled() throws Exception { @Test public void test051ModifyUserJackDisable() throws Exception { - final String TEST_NAME = "test051ModifyUserJackDisable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -200,10 +175,8 @@ public void test051ModifyUserJackDisable() throws Exception { @Test public void test052ModifyUserJackNull() throws Exception { - final String TEST_NAME = "test052ModifyUserJackNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -230,10 +203,8 @@ public void test052ModifyUserJackNull() throws Exception { @Test public void test055ModifyUserJackEnable() throws Exception { - final String TEST_NAME = "test055ModifyUserJackEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -261,10 +232,8 @@ public void test055ModifyUserJackEnable() throws Exception { @Test public void test056RecomputeUserJackEffectiveEnable() throws Exception { - final String TEST_NAME = "test056RecomputeUserJackEffectiveEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); @@ -304,19 +273,14 @@ public void test056RecomputeUserJackEffectiveEnable() throws Exception { assertValidity(userJackAfter, null); assertEffectiveStatus(userJackAfter, ActivationStatusType.ENABLED); - TestUtil.assertModifyTimestamp(userJackAfter, start, end); - - } @Test public void test060ModifyUserJackLifecycleActive() throws Exception { - final String TEST_NAME = "test060ModifyUserJackLifecycleActive"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -344,10 +308,8 @@ public void test060ModifyUserJackLifecycleActive() throws Exception { @Test public void test061ModifyUserJackLifecycleDraft() throws Exception { - final String TEST_NAME = "test061ModifyUserJackLifecycleDraft"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -375,10 +337,8 @@ public void test061ModifyUserJackLifecycleDraft() throws Exception { @Test public void test065ModifyUserJackLifecycleDeprecated() throws Exception { - final String TEST_NAME = "test065ModifyUserJackLifecycleDeprecated"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -406,10 +366,8 @@ public void test065ModifyUserJackLifecycleDeprecated() throws Exception { @Test public void test068ModifyUserJackLifecycleArchived() throws Exception { - final String TEST_NAME = "test068ModifyUserJackLifecycleArchived"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -436,10 +394,8 @@ public void test068ModifyUserJackLifecycleArchived() throws Exception { @Test public void test069ModifyUserJackLifecycleNull() throws Exception { - final String TEST_NAME = "test069ModifyUserJackLifecycleNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -466,10 +422,8 @@ public void test069ModifyUserJackLifecycleNull() throws Exception { @Test public void test100ModifyUserJackAssignAccount() throws Exception { - final String TEST_NAME = "test100ModifyUserJackAssignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -526,7 +480,7 @@ public void test100ModifyUserJackAssignAccount() throws Exception { dummyAuditService.assertExecutionSuccess(); Collection> executionDeltas = dummyAuditService.getExecutionDeltas(); boolean found = false; - for (ObjectDeltaOperation executionDelta: executionDeltas) { + for (ObjectDeltaOperation executionDelta : executionDeltas) { ObjectDelta objectDelta = executionDelta.getObjectDelta(); if (objectDelta.getObjectTypeClass() == ShadowType.class) { PropertyDelta enableTimestampDelta = objectDelta.findPropertyDelta(PATH_ACTIVATION_ENABLE_TIMESTAMP); @@ -540,10 +494,8 @@ public void test100ModifyUserJackAssignAccount() throws Exception { @Test public void test101ModifyUserJackDisable() throws Exception { - final String TEST_NAME = "test101ModifyUserJackDisable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -595,7 +547,6 @@ public void test102ModifyUserJackEnable() throws Exception { assertEnableTimestampFocus(userJack, startTime, endTime); } - /** * Modify account activation. User's activation should be unchanged */ @@ -635,10 +586,8 @@ public void test111ModifyAccountJackDisable() throws Exception { */ @Test public void test112UserJackRecompute() throws Exception { - final String TEST_NAME = "test112UserJackRecompute"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -674,10 +623,8 @@ public void test112UserJackRecompute() throws Exception { */ @Test public void test114ModifyUserJackEnable() throws Exception { - final String TEST_NAME = "test114ModifyUserJackEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -711,10 +658,8 @@ public void test114ModifyUserJackEnable() throws Exception { */ @Test public void test115ModifyUserJackAdministrativeStatusNull() throws Exception { - final String TEST_NAME = "test115ModifyUserJackAdministrativeStatusNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -749,10 +694,8 @@ public void test115ModifyUserJackAdministrativeStatusNull() throws Exception { */ @Test public void test118ModifyJackActivationUserAndAccount() throws Exception { - final String TEST_NAME = "test118ModifyJackActivationUserAndAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -844,14 +787,11 @@ public void test120ModifyUserJackAssignAccountDummyRed() throws Exception { */ @Test public void test121ModifyJackUserAndAccountRed() throws Exception { - final String TEST_NAME = "test121ModifyJackUserAndAccountRed"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - ObjectDelta userDelta = createModifyUserReplaceDelta(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, ActivationStatusType.DISABLED); ObjectDelta accountDelta = createModifyAccountShadowReplaceDelta(accountRedOid, getDummyResourceObject(), @@ -923,10 +863,8 @@ public void test130ModifyAccountDefaultAndRed() throws Exception { */ @Test public void test138ModifyJackEnabled() throws Exception { - final String TEST_NAME = "test138ModifyJackEnabled"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -953,10 +891,8 @@ public void test138ModifyJackEnabled() throws Exception { */ @Test public void test139ModifyUserJackUnAssignAccountDummyRed() throws Exception { - final String TEST_NAME = "test139ModifyUserJackUnAssignAccountDummyRed"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1256,10 +1192,8 @@ public void test152ModifyAccountsJackDisable() throws Exception { */ @Test public void test153ModifyAccountsJackEnable() throws Exception { - final String TEST_NAME = "test153ModifyAccountsJackEnable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1386,7 +1320,7 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { dummyAuditService.assertExecutionSuccess(); Collection> executionDeltas = dummyAuditService.getExecutionDeltas(); boolean found = false; - for (ObjectDeltaOperation executionDelta: executionDeltas) { + for (ObjectDeltaOperation executionDelta : executionDeltas) { ObjectDelta objectDelta = executionDelta.getObjectDelta(); if (objectDelta.getObjectTypeClass() == ShadowType.class) { // Actually, there should be no F_TRIGGER delta! It was there by mistake. @@ -1395,7 +1329,7 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { // } PropertyDelta enableTimestampDelta = objectDelta.findPropertyDelta(PATH_ACTIVATION_ENABLE_TIMESTAMP); display("Audit enableTimestamp delta", enableTimestampDelta); - assertNotNull("EnableTimestamp delta vanished from audit record, delta: "+objectDelta, enableTimestampDelta); + assertNotNull("EnableTimestamp delta vanished from audit record, delta: " + objectDelta, enableTimestampDelta); found = true; } } @@ -1404,10 +1338,8 @@ public void test160ModifyUserJackAssignAccountKhaki() throws Exception { @Test public void test170GetAccountUnlocked() throws Exception { - final String TEST_NAME = "test170GetAccountUnlocked"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1427,10 +1359,8 @@ public void test170GetAccountUnlocked() throws Exception { @Test public void test172GetAccountLocked() throws Exception { - final String TEST_NAME = "test172GetAccountLocked"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1454,10 +1384,8 @@ public void test172GetAccountLocked() throws Exception { @Test public void test174ModifyAccountUnlock() throws Exception { - final String TEST_NAME = "test174ModifyAccountUnlock"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1488,10 +1416,8 @@ public void test174ModifyAccountUnlock() throws Exception { @Test public void test176ModifyUserUnlock() throws Exception { - final String TEST_NAME = "test176ModifyUserUnlock"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1520,13 +1446,10 @@ public void test176ModifyUserUnlock() throws Exception { checkAdminStatusFor15x(userJack, true, true, true); } - @Test public void test199DeleteUserJack() throws Exception { - final String TEST_NAME = "test199DeleteUserJack"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1556,11 +1479,9 @@ public void test199DeleteUserJack() throws Exception { @Test public void test200AddUserLargo() throws Exception { - final String TEST_NAME = "test200AddUserLargo"; - // GIVEN long startMillis = System.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userLargo = PrismTestUtil.parseObject(USER_LARGO_FILE); @@ -1581,10 +1502,8 @@ public void test200AddUserLargo() throws Exception { @Test public void test205ModifyUserLargoAssignAccount() throws Exception { - final String TEST_NAME = "test205ModifyUserLargoAssignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1619,11 +1538,9 @@ public void test205ModifyUserLargoAssignAccount() throws Exception { @Test public void test210ModifyLargoValidTo10MinsAgo() throws Exception { - final String TEST_NAME = "test210ModifyLargoValidTo10MinsAgo"; - // GIVEN long startMillis = System.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); XMLGregorianCalendar tenMinutesAgo = XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis() - 10 * 60 * 1000); @@ -1656,11 +1573,9 @@ public void test210ModifyLargoValidTo10MinsAgo() throws Exception { @Test public void test211ModifyLargoValidToManana() throws Exception { - final String TEST_NAME = "test211ModifyLargoValidToManana"; - // GIVEN long startMillis = System.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); manana = XmlTypeConverter.createXMLGregorianCalendar(System.currentTimeMillis() + 10 * 24 * 60 * 60 * 1000); @@ -1697,10 +1612,8 @@ public void test211ModifyLargoValidToManana() throws Exception { */ @Test public void test212SeeLargoTomorrow() throws Exception { - final String TEST_NAME = "test212SeeLargoTomorrow"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Let's play with the clock, move the time to tomorrow @@ -1743,7 +1656,7 @@ public void test213HastaLaMananaLargo() throws Exception { OperationResult result = task.getResult(); // Let's play with the clock, move the time forward 20 days - long crrentNow = System.currentTimeMillis() + 20 *24 * 60 * 60 * 1000; + long crrentNow = System.currentTimeMillis() + 20 * 24 * 60 * 60 * 1000; clock.override(crrentNow); // WHEN @@ -1774,11 +1687,9 @@ public void test213HastaLaMananaLargo() throws Exception { @Test public void test215ModifyLargoRemoveValidTo() throws Exception { - final String TEST_NAME = "test215ModifyLargoRemoveValidTo"; - // GIVEN long startMillis = clock.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -1810,11 +1721,9 @@ public void test215ModifyLargoRemoveValidTo() throws Exception { @Test public void test217ModifyLargoRemoveValidFrom() throws Exception { - final String TEST_NAME = "test217ModifyLargoRemoveValidFrom"; - // GIVEN long startMillis = clock.currentTimeMillis(); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -1851,10 +1760,8 @@ public void test217ModifyLargoRemoveValidFrom() throws Exception { */ @Test public void test230JackUnassignRepoRecompute() throws Exception { - final String TEST_NAME = "test230JackUnassignRepoRecompute"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); addObject(USER_JACK_FILE); @@ -1882,10 +1789,8 @@ public void test230JackUnassignRepoRecompute() throws Exception { */ @Test public void test231JackRecomputeReconcile() throws Exception { - final String TEST_NAME = "test231JackRecomputeReconcile"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2127,7 +2032,6 @@ public void test249DeleteUserRapp() throws Exception { assertNoDummyAccount(USER_RAPP_USERNAME); } - /** * Test reading of validity data through shadow */ @@ -2203,10 +2107,8 @@ public void test310ImportAccountsFromDummyGreen() throws Exception { @Test public void test350AssignMancombBlueAccount() throws Exception { - final String TEST_NAME = "test350AssignMancombBlueAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2229,10 +2131,8 @@ public void test350AssignMancombBlueAccount() throws Exception { @Test public void test352AssignMancombBlackAccount() throws Exception { - final String TEST_NAME = "test352AssignMancombBlackAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2261,10 +2161,8 @@ public void test352AssignMancombBlackAccount() throws Exception { @Test public void test355MancombModifyAdministrativeStatusNull() throws Exception { - final String TEST_NAME = "test355MancombModifyAdministrativeStatusNull"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2295,13 +2193,11 @@ public void test355MancombModifyAdministrativeStatusNull() throws Exception { @Test public void test400AddHerman() throws Exception { - final String TEST_NAME = "test400AddHerman"; - // WHEN addObject(USER_HERMAN_FILE); // THEN - // Make sure that it is effectivelly enabled + // Make sure that it is effectively enabled PrismObject userHermanAfter = getUser(USER_HERMAN_OID); assertEffectiveActivation(userHermanAfter, ActivationStatusType.ENABLED); } @@ -2311,10 +2207,8 @@ public void test400AddHerman() throws Exception { */ @Test public void test410AssignHermanKhakiAccount() throws Exception { - final String TEST_NAME = "test410AssignHermanKhakiAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -2337,85 +2231,82 @@ public void test410AssignHermanKhakiAccount() throws Exception { khakiAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME)); } - @Test public void test500CheckRolePirateInitial() throws Exception { - test5X0CheckInitial("test500CheckRolePirateInitial", RoleType.class, ROLE_PIRATE_OID); + test5X0CheckInitial(RoleType.class, ROLE_PIRATE_OID); } @Test public void test501RolePirateRecompute() throws Exception { - test5X1Recompute("test501RolePirateRecompute", RoleType.class, ROLE_PIRATE_OID); + test5X1Recompute(RoleType.class, ROLE_PIRATE_OID); } @Test public void test502ModifyRolePirateDisable() throws Exception { - test5X2ModifyDisable("test502ModifyRolePirateDisable", RoleType.class, ROLE_PIRATE_OID); + test5X2ModifyDisable(RoleType.class, ROLE_PIRATE_OID); } @Test public void test504ModifyRolePirateEnable() throws Exception { - test5X4ModifyEnable("test504ModifyRolePirateEnable", RoleType.class, ROLE_PIRATE_OID); + test5X4ModifyEnable(RoleType.class, ROLE_PIRATE_OID); } @Test public void test505RolePirateRecompute() throws Exception { - test5X5Recompute("test505RolePirateRecompute", RoleType.class, ROLE_PIRATE_OID); + test5X5Recompute(RoleType.class, ROLE_PIRATE_OID); } - @Test public void test510CheckOrgScummBarInitial() throws Exception { - test5X0CheckInitial("test510CheckOrgScummBarInitial", OrgType.class, ORG_SCUMM_BAR_OID); + test5X0CheckInitial(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test511OrgScummBarRecompute() throws Exception { - test5X1Recompute("test511OrgScummBarRecompute", OrgType.class, ORG_SCUMM_BAR_OID); + test5X1Recompute(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test512ModifyOrgScummBarDisable() throws Exception { - test5X2ModifyDisable("test512ModifyOrgScummBarDisable", OrgType.class, ORG_SCUMM_BAR_OID); + test5X2ModifyDisable(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test514ModifyOrgScummBarEnable() throws Exception { - test5X4ModifyEnable("test514ModifyOrgScummBarEnable", OrgType.class, ORG_SCUMM_BAR_OID); + test5X4ModifyEnable(OrgType.class, ORG_SCUMM_BAR_OID); } @Test public void test515OrgScummBarRecompute() throws Exception { - test5X5Recompute("test515OrgScummBarRecompute", OrgType.class, ORG_SCUMM_BAR_OID); + test5X5Recompute(OrgType.class, ORG_SCUMM_BAR_OID); } - @Test public void test520CheckSerivceSeaMonkeyInitial() throws Exception { - test5X0CheckInitial("test520CheckSerivceSeaMonkeyInitial", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X0CheckInitial(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test521SerivceSeaMonkeyRecompute() throws Exception { - test5X1Recompute("test521SerivceSeaMonkeyRecompute", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X1Recompute(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test522ModifySerivceSeaMonkeyDisable() throws Exception { - test5X2ModifyDisable("test522ModifySerivceSeaMonkeyDisable", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X2ModifyDisable(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test524ModifySerivceSeaMonkeyEnable() throws Exception { - test5X4ModifyEnable("test524ModifySerivceSeaMonkeyEnable", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X4ModifyEnable(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } @Test public void test525SerivceSeaMonkeyRecompute() throws Exception { - test5X5Recompute("test525SerivceSeaMonkeyRecompute", ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); + test5X5Recompute(ServiceType.class, SERVICE_SHIP_SEA_MONKEY_OID); } - private void test5X0CheckInitial(final String TEST_NAME, Class type, String oid) throws Exception { + private void test5X0CheckInitial(Class type, String oid) throws Exception { // GIVEN, WHEN // this happens during test initialization when the role is added @@ -2432,18 +2323,18 @@ private void test5X0CheckInitial(final String TEST_NAME, C * Make sure that recompute properly updates the effective status. * MID-2877 */ - private void test5X1Recompute(final String TEST_NAME, Class type, String oid) throws Exception { + private void test5X1Recompute(Class type, String oid) throws Exception { - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - // WHEN + when(); modelService.recompute(type, oid, null, task, result); - // THEN + then(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2458,19 +2349,18 @@ private void test5X1Recompute(final String TEST_NAME, Clas /** * MID-2877 */ - private void test5X2ModifyDisable(final String TEST_NAME, Class type, String oid) throws Exception { - - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + private void test5X2ModifyDisable(Class type, String oid) throws Exception { + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - // WHEN + when(); modifyObjectReplaceProperty(type, oid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.DISABLED); - // THEN + then(); XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2489,19 +2379,17 @@ private void test5X2ModifyDisable(final String TEST_NAME, /** * MID-2877 */ - private void test5X4ModifyEnable(final String TEST_NAME, Class type, String oid) throws Exception { - - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + private void test5X4ModifyEnable(Class type, String oid) throws Exception { + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); - XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - // WHEN + when(); modifyObjectReplaceProperty(type, oid, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, task, result, ActivationStatusType.ENABLED); - // THEN + then(); XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2520,18 +2408,17 @@ private void test5X4ModifyEnable(final String TEST_NAME, C /** * Make sure that recompute does not destroy anything. */ - public void test5X5Recompute(final String TEST_NAME, Class type, String oid) throws Exception { - - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + public void test5X5Recompute(Class type, String oid) throws Exception { + given(); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); dummyAuditService.clear(); - // WHEN + when(); modelService.recompute(type, oid, null, task, result); - // THEN + then(); result.computeStatus(); TestUtil.assertSuccess(result); @@ -2550,8 +2437,6 @@ public void test5X5Recompute(final String TEST_NAME, Class // attempt to simulate MID-3348 (unsuccessful for now) @Test public void test600AddUser1() throws Exception { - final String TEST_NAME = "test600AddUser1"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2595,12 +2480,10 @@ private void checkSuspendedAttribute(DummyAccount dummyAccount, Boolean expected @Test public void test610EnableUser1() throws Exception { - final String TEST_NAME = "test610EnableUser1"; - // GIVEN PrismObject user1 = findUserByUsername("user1"); - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); Collection> deltas = @@ -2631,10 +2514,8 @@ public void test610EnableUser1() throws Exception { */ @Test public void test700ModifyJackRemoveAdministrativeStatus() throws Exception { - final String TEST_NAME = "test700ModifyJackRemoveAdministrativeStatus"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2682,10 +2563,8 @@ public void test700ModifyJackRemoveAdministrativeStatus() throws Exception { */ @Test public void test702ModifyJackFuneralTimestampBeforeNow() throws Exception { - final String TEST_NAME = "test702ModifyJackFuneralTimestampBeforeNow"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2727,10 +2606,8 @@ public void test702ModifyJackFuneralTimestampBeforeNow() throws Exception { */ @Test public void test704ModifyJackFuneralTimestampAfterNow() throws Exception { - final String TEST_NAME = "test704ModifyJackFuneralTimestampAfterNow"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2768,10 +2645,8 @@ public void test704ModifyJackFuneralTimestampAfterNow() throws Exception { */ @Test public void test750AddAndDeleteUserWithPrecreate() throws Exception { - final String TEST_NAME = "test750AddAndDeleteUserWithPrecreate"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -2785,12 +2660,12 @@ public void test750AddAndDeleteUserWithPrecreate() throws Exception { UserType user = new UserType(prismContext) .name("test750") .beginAssignment() - .beginConstruction() - .resourceRef(RESOURCE_DUMMY_PRECREATE.oid, ResourceType.COMPLEX_TYPE) - .end() + .beginConstruction() + .resourceRef(RESOURCE_DUMMY_PRECREATE.oid, ResourceType.COMPLEX_TYPE) + .end() .end() .beginActivation() - .validFrom(yesterday) + .validFrom(yesterday) .end(); String oid = addObject(user.asPrismObject(), task, result); assertSuccess(result); @@ -2813,8 +2688,8 @@ private void assertDummyActivationEnabledState(String userId, Boolean expectedEn private void assertDummyActivationEnabledState(String instance, String userId, Boolean expectedEnabled) throws SchemaViolationException, ConflictException, InterruptedException { DummyAccount account = getDummyAccount(instance, userId); - assertNotNull("No dummy account "+userId, account); - assertEquals("Wrong enabled flag in dummy '"+instance+"' account "+userId, expectedEnabled, account.isEnabled()); + assertNotNull("No dummy account " + userId, account); + assertEquals("Wrong enabled flag in dummy '" + instance + "' account " + userId, expectedEnabled, account.isEnabled()); } private void assertDummyEnabled(String userId) throws SchemaViolationException, ConflictException, InterruptedException { @@ -2835,35 +2710,35 @@ private void assertDummyDisabled(String instance, String userId) throws SchemaVi private void assertValidity(PrismObject focus, TimeIntervalStatusType expectedValidityStatus) { ActivationType activation = focus.asObjectable().getActivation(); - assertNotNull("No activation in "+focus, activation); - assertEquals("Unexpected validity status in "+focus, expectedValidityStatus, activation.getValidityStatus()); + assertNotNull("No activation in " + focus, activation); + assertEquals("Unexpected validity status in " + focus, expectedValidityStatus, activation.getValidityStatus()); } private void assertValidityTimestamp(PrismObject user, long expected) { ActivationType activation = user.asObjectable().getActivation(); - assertNotNull("No activation in "+user, activation); + assertNotNull("No activation in " + user, activation); XMLGregorianCalendar validityChangeTimestamp = activation.getValidityChangeTimestamp(); - assertNotNull("No validityChangeTimestamp in "+user, validityChangeTimestamp); + assertNotNull("No validityChangeTimestamp in " + user, validityChangeTimestamp); assertEquals("wrong validityChangeTimestamp", expected, XmlTypeConverter.toMillis(validityChangeTimestamp)); } private void assertValidityTimestamp(PrismObject user, XMLGregorianCalendar expected) { ActivationType activation = user.asObjectable().getActivation(); - assertNotNull("No activation in "+user, activation); + assertNotNull("No activation in " + user, activation); XMLGregorianCalendar validityChangeTimestamp = activation.getValidityChangeTimestamp(); - assertNotNull("No validityChangeTimestamp in "+user, validityChangeTimestamp); + assertNotNull("No validityChangeTimestamp in " + user, validityChangeTimestamp); assertEquals("wrong validityChangeTimestamp", expected, validityChangeTimestamp); } private void assertValidityTimestamp(PrismObject user, long lowerBound, long upperBound) { ActivationType activation = user.asObjectable().getActivation(); - assertNotNull("No activation in "+user, activation); + assertNotNull("No activation in " + user, activation); XMLGregorianCalendar validityChangeTimestamp = activation.getValidityChangeTimestamp(); - assertNotNull("No validityChangeTimestamp in "+user, validityChangeTimestamp); + assertNotNull("No validityChangeTimestamp in " + user, validityChangeTimestamp); long validityMillis = XmlTypeConverter.toMillis(validityChangeTimestamp); if (validityMillis >= lowerBound && validityMillis <= upperBound) { return; } - AssertJUnit.fail("Expected validityChangeTimestamp to be between "+lowerBound+" and "+upperBound+", but it was "+validityMillis); + AssertJUnit.fail("Expected validityChangeTimestamp to be between " + lowerBound + " and " + upperBound + ", but it was " + validityMillis); } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java index 630832a6d11..6ce6c305a6b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestCaseIgnore.java @@ -7,7 +7,6 @@ package com.evolveum.midpoint.model.intest; import com.evolveum.icf.dummy.resource.DummyGroup; -import com.evolveum.midpoint.model.intest.rbac.TestRbac; import com.evolveum.midpoint.prism.PrismConstants; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; @@ -74,7 +73,7 @@ public class TestCaseIgnore extends AbstractInitializedModelIntegrationTest { private static final String GROUP_DUMMY_FOOLS_NAME = "FoOlS"; - @Autowired(required = true) + @Autowired protected MatchingRuleRegistry matchingRuleRegistry; private MatchingRule caseIgnoreMatchingRule; @@ -100,17 +99,13 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test000Sanity() throws Exception { - final String TEST_NAME="test000Sanity"; - assertShadows(5); } @Test public void test131ModifyUserJackAssignAccount() throws Exception { - final String TEST_NAME="test131ModifyUserJackAssignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_UPCASE_OID, null, true); @@ -159,11 +154,9 @@ public void test131ModifyUserJackAssignAccount() throws Exception { } @Test - public void test133SeachAccountShadows() throws Exception { - final String TEST_NAME="test133SeachAccountShadows"; - + public void test133SearchAccountShadows() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_UPCASE_OID, @@ -213,10 +206,8 @@ public void test133SeachAccountShadows() throws Exception { @Test public void test139ModifyUserJackUnassignAccount() throws Exception { - final String TEST_NAME = "test139ModifyUserJackUnassignAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestCaseIgnore.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); @@ -252,9 +243,7 @@ public void test139ModifyUserJackUnassignAccount() throws Exception { @Test public void test150JackAssignRoleX() throws Exception { - final String TEST_NAME = "test150JackAssignRoleX"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -298,9 +287,7 @@ public void test150JackAssignRoleX() throws Exception { @Test public void test152GetJack() throws Exception { - final String TEST_NAME = "test152GetJack"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -339,9 +326,7 @@ public void test152GetJack() throws Exception { @Test public void test159JackUnAssignRoleX() throws Exception { - final String TEST_NAME = "test159JackUnAssignRoleX"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -370,9 +355,7 @@ public void test159JackUnAssignRoleX() throws Exception { @Test public void test160JackAssignRoleBasic() throws Exception { - final String TEST_NAME = "test160JackAssignRoleBasic"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -418,9 +401,7 @@ public void test160JackAssignRoleBasic() throws Exception { @Test public void test161JackAssignRoleJoker() throws Exception { - final String TEST_NAME = "test161JackAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -470,9 +451,7 @@ public void test161JackAssignRoleJoker() throws Exception { @Test public void test165JackUnAssignRoleJoker() throws Exception { - final String TEST_NAME = "test165JackUnAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -518,9 +497,7 @@ public void test165JackUnAssignRoleJoker() throws Exception { @Test public void test169JackUnAssignRoleBasic() throws Exception { - final String TEST_NAME = "test169JackUnAssignRoleBasic"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -552,9 +529,7 @@ public void test169JackUnAssignRoleBasic() throws Exception { @Test public void test170JackAssignRoleJoker() throws Exception { - final String TEST_NAME = "test170JackAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -599,9 +574,7 @@ public void test170JackAssignRoleJoker() throws Exception { @Test public void test179JackUnAssignRoleJoker() throws Exception { - final String TEST_NAME = "test179JackUnAssignRoleJoker"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); @@ -641,9 +614,7 @@ public void test179JackUnAssignRoleJoker() throws Exception { */ @Test public void test200GuybrushAssignRoleFools() throws Exception { - final String TEST_NAME = "test200GuybrushAssignRoleFools"; - - Task task = taskManager.createTaskInstance(TestRbac.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assertShadows(5); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java index b5a9d804ce5..0bbc07329ef 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConnectorDummyFake.java @@ -6,14 +6,11 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.util.Collection; import java.util.List; -import com.evolveum.midpoint.prism.delta.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -24,6 +21,9 @@ import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismReference; +import com.evolveum.midpoint.prism.delta.DiffUtil; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.schema.util.ResourceTypeUtil; @@ -31,14 +31,7 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; @@ -49,9 +42,8 @@ * fake dummy connector. Test upgrades and downgrades of connector version. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestConnectorDummyFake extends AbstractConfiguredModelIntegrationTest { @@ -85,8 +77,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010ListConnectors() throws Exception { - final String TEST_NAME = "test010ListConnectors"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -100,7 +90,7 @@ public void test010ListConnectors() throws Exception { TestUtil.assertSuccess("getObject result", result); assertEquals("Unexpected number of connectors", 12, connectors.size()); - for(PrismObject connector: connectors) { + for (PrismObject connector : connectors) { display("Connector", connector); ConnectorType connectorType = connector.asObjectable(); if (CONNECTOR_DUMMY_TYPE.equals(connectorType.getConnectorType())) { @@ -122,8 +112,6 @@ public void test010ListConnectors() throws Exception { @Test public void test020ImportFakeResource() throws Exception { - final String TEST_NAME = "test020ImportFakeResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -146,24 +134,19 @@ public void test020ImportFakeResource() throws Exception { @Test public void test021TestFakeResource() throws Exception { - final String TEST_NAME = "test021TestFakeResource"; - // GIVEN Task task = getTestTask(); - OperationResult result = task.getResult(); // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_FAKE_OID, task); // THEN - display("testResource result", testResult); + display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } @Test public void test022ListAccountsFakeResource() throws Exception { - final String TEST_NAME = "test022ListAccountsFakeResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -173,16 +156,14 @@ public void test022ListAccountsFakeResource() throws Exception { // THEN result.computeStatus(); - display("listAccounts result", result); + display("listAccounts result", result); TestUtil.assertSuccess("listAccounts result", result); - assertEquals("Unexpected number of accounts: "+accounts, 1, accounts.size()); + assertEquals("Unexpected number of accounts: " + accounts, 1, accounts.size()); } @Test public void test030ImportDummyResource() throws Exception { - final String TEST_NAME = "test030ImportDummyResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -205,24 +186,19 @@ public void test030ImportDummyResource() throws Exception { @Test public void test031TestDummyResource() throws Exception { - final String TEST_NAME = "test031TestDummyResource"; - // GIVEN Task task = getTestTask(); - OperationResult result = task.getResult(); // WHEN OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); // THEN - display("testResource result", testResult); + display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } @Test public void test032ListAccountsDummyResource() throws Exception { - final String TEST_NAME = "test032ListAccountsDummyResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -233,7 +209,7 @@ public void test032ListAccountsDummyResource() throws Exception { // THEN assertSuccess(result); - assertEquals("Unexpected number of accounts: "+accounts, 3, accounts.size()); + assertEquals("Unexpected number of accounts: " + accounts, 3, accounts.size()); } /** @@ -242,8 +218,6 @@ public void test032ListAccountsDummyResource() throws Exception { */ @Test public void test100UpgradeModelAddDelete() throws Exception { - final String TEST_NAME = "test100UpgradeModelAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -270,14 +244,11 @@ public void test100UpgradeModelAddDelete() throws Exception { // THEN assertSuccess(result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test150DowngradeModelAddDelete() throws Exception { - final String TEST_NAME = "test150DowngradeModelAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -305,8 +276,6 @@ public void test150DowngradeModelAddDelete() throws Exception { @Test public void test200UpgradeModelReplace() throws Exception { - final String TEST_NAME = "test200UpgradeModelReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -326,14 +295,11 @@ public void test200UpgradeModelReplace() throws Exception { // THEN assertSuccess("executeChanges result", result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test250DowngradeModelReplace() throws Exception { - final String TEST_NAME = "test250DowngradeModelReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -358,8 +324,6 @@ public void test250DowngradeModelReplace() throws Exception { @Test public void test300UpgradeRawAddDelete() throws Exception { - final String TEST_NAME = "test300UpgradeRawAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -384,14 +348,11 @@ public void test300UpgradeRawAddDelete() throws Exception { // THEN assertSuccess(result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test350DowngradeRawAddDelete() throws Exception { - final String TEST_NAME = "test350DowngradeRawAddDelete"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -416,7 +377,7 @@ public void test350DowngradeRawAddDelete() throws Exception { // THEN result.computeStatus(); - display("executeChanges result", result); + display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); assertDowngrade(dummyResourceModelBefore); @@ -424,8 +385,6 @@ public void test350DowngradeRawAddDelete() throws Exception { @Test public void test400UpgradeRawReplace() throws Exception { - final String TEST_NAME = "test400UpgradeRawReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -447,17 +406,14 @@ public void test400UpgradeRawReplace() throws Exception { // THEN result.computeStatus(); - display("executeChanges result", result); + display("executeChanges result", result); TestUtil.assertSuccess("executeChanges result", result); - assertUpgrade(TEST_NAME, dummyResourceModelBefore); + assertUpgrade(dummyResourceModelBefore); } - @Test public void test450DowngradeRawReplace() throws Exception { - final String TEST_NAME = "test450DowngradeRawReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -482,8 +438,8 @@ public void test450DowngradeRawReplace() throws Exception { assertDowngrade(dummyResourceModelBefore); } - private void assertUpgrade(final String TEST_NAME, PrismObject dummyResourceModelBefore) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { - Task task = taskManager.createTaskInstance(TestConnectorDummyFake.class.getName() + ".assertUpgrade"); + private void assertUpgrade(PrismObject dummyResourceModelBefore) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { + Task task = createPlainTask("assertUpgrade"); OperationResult result = task.getResult(); // Check if the changes went well in the repo @@ -494,7 +450,7 @@ private void assertUpgrade(final String TEST_NAME, PrismObject dum assertEquals("Wrong connectorRef in fake resource (repo)", connectorDummyOid, repoResource.asObjectable().getConnectorRef().getOid()); - display("HEREHERE: "+TEST_NAME); + displayHEREHERE(); // Check if resource view of the model has changed as well resourceDummyFake = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_FAKE_OID, null, task, result); display("Upgraded fake resource (model)", resourceDummyFake); @@ -511,9 +467,9 @@ private void assertUpgrade(final String TEST_NAME, PrismObject dum dummyResourceModelAfter.asObjectable().setFetchResult(null); ObjectDelta dummyResourceDiff = DiffUtil.diff(dummyResourceModelBefore, dummyResourceModelAfter); display("Dummy resource diff", dummyResourceDiff); - assertTrue("Ha! Someone touched the other resource! Off with his head! diff:"+dummyResourceDiff, dummyResourceDiff.isEmpty()); + assertTrue("Ha! Someone touched the other resource! Off with his head! diff:" + dummyResourceDiff, dummyResourceDiff.isEmpty()); - testResources(3,3); + testResources(3, 3); } private void assertDowngrade(PrismObject dummyResourceModelBefore) throws ObjectNotFoundException, SchemaException, SecurityViolationException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { @@ -541,9 +497,9 @@ private void assertDowngrade(PrismObject dummyResourceModelBefore) dummyResourceModelAfter.asObjectable().setFetchResult(null); ObjectDelta dummyResourceDiff = DiffUtil.diff(dummyResourceModelBefore, dummyResourceModelAfter); display("Dummy resource diff", dummyResourceDiff); - assertTrue("Ha! Someone touched the other resource! Off with his head! diff:"+dummyResourceDiff, dummyResourceDiff.isEmpty()); + assertTrue("Ha! Someone touched the other resource! Off with his head! diff:" + dummyResourceDiff, dummyResourceDiff.isEmpty()); - testResources(3,1); + testResources(3, 1); } private void testResources(int numDummyAccounts, int numFakeAccounts) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { @@ -553,11 +509,11 @@ private void testResources(int numDummyAccounts, int numFakeAccounts) throws Obj purgeResourceSchema(RESOURCE_DUMMY_FAKE_OID); OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_FAKE_OID, task); - display("testResource fake result", testResult); + display("testResource fake result", testResult); TestUtil.assertSuccess("testResource fake result", testResult); testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); - display("testResource dummy result", testResult); + display("testResource dummy result", testResult); TestUtil.assertSuccess("testResource dummy result", testResult); assertResourceAccounts(resourceDummy, numDummyAccounts); @@ -573,12 +529,10 @@ private void assertResourceAccounts(PrismObject resource, int numA // THEN result.computeStatus(); - display("listAccounts result "+resource, result); - TestUtil.assertSuccess("listAccounts result "+resource, result); + display("listAccounts result " + resource, result); + TestUtil.assertSuccess("listAccounts result " + resource, result); - assertEquals("Unexpected number of accounts on "+resource+": "+accounts, numAccounts, accounts.size()); + assertEquals("Unexpected number of accounts on " + resource + ": " + accounts, numAccounts, accounts.size()); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java index a328bd9bbec..5605002acb8 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestConsistencySimple.java @@ -61,90 +61,91 @@ private enum ResourceObjectOperation { KEEP, DELETE } private ObjectClassComplexTypeDefinition getAccountObjectClassDefinition() throws SchemaException { ResourceSchema schema = RefinedResourceSchemaImpl.getResourceSchema(getDummyResourceObject(), prismContext); + assertNotNull(schema); return schema.findObjectClassDefinition(dummyResourceCtl.getAccountObjectClassQName()); } @Test public void test100Reconcile_Keep_Keep() throws Exception { - executeTest("test100Reconcile_Keep_Keep", FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test110Recompute_Keep_Keep() throws Exception { - executeTest("test110Recompute_Keep_Keep", FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test120Reconcile_Unlink_Keep() throws Exception { - executeTest("test120Reconcile_Unlink_Keep", FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test130Recompute_Unlink_Keep() throws Exception { - executeTest("test130Recompute_Unlink_Keep", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test140Reconcile_UnlinkTombstone_Keep() throws Exception { - executeTest("test140Reconcile_UnlinkTombstone_Keep", FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test150Recompute_UnlinkTombstone_Keep() throws Exception { - executeTest("test150Recompute_UnlinkTombstone_Keep", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test160Reconcile_Delete_Keep() throws Exception { - executeTest("test160Reconcile_Delete_Keep", FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } @Test public void test170Recompute_Delete_Keep() throws Exception { - executeTest("test170Recompute_Delete_Keep", FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } @Test public void test200Reconcile_Keep_Delete() throws Exception { - executeTest("test200Reconcile_Keep_Delete", FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test210Recompute_Keep_Delete() throws Exception { - executeTest("test210Recompute_Keep_Delete", FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.KEEP, ResourceObjectOperation.KEEP); } @Test public void test220Reconcile_Unlink_Delete() throws Exception { - executeTest("test220Reconcile_Unlink_Delete", FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test230Recompute_Unlink_Delete() throws Exception { - executeTest("test230Recompute_Unlink_Delete", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK, ResourceObjectOperation.KEEP); } @Test public void test240Reconcile_UnlinkTombstone_Delete() throws Exception { - executeTest("test240Reconcile_UnlinkTombstone_Delete", FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test250Recompute_UnlinkTombstone_Delete() throws Exception { - executeTest("test250Recompute_UnlinkTombstone_Delete", FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.UNLINK_AND_TOMBSTONE, ResourceObjectOperation.KEEP); } @Test public void test260Reconcile_Delete_Delete() throws Exception { - executeTest("test260Reconcile_Delete_Delete", FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECONCILE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } @Test public void test270Recompute_Delete_Delete() throws Exception { - executeTest("test270Recompute_Delete_Delete", FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); + executeTest(FocusOperation.RECOMPUTE, ShadowOperation.DELETE, ResourceObjectOperation.KEEP); } - private void executeTest(final String TEST_NAME, FocusOperation focusOperation, ShadowOperation shadowOperation, + private void executeTest(FocusOperation focusOperation, ShadowOperation shadowOperation, ResourceObjectOperation resourceObjectOperation) throws Exception { // GIVEN @@ -162,7 +163,6 @@ private void executeTest(final String TEST_NAME, FocusOperation focusOperation, display("Shadow", shadowBefore); if (shadowOperation != ShadowOperation.KEEP) { - @SuppressWarnings("unchecked") ObjectDelta removeLinkRefDelta = deltaFor(UserType.class) .item(UserType.F_LINK_REF).replace() .asObjectDelta(USER_JACK_OID); @@ -175,7 +175,6 @@ private void executeTest(final String TEST_NAME, FocusOperation focusOperation, assertNoObject(ShadowType.class, shadowBefore.getOid()); } else { if (shadowOperation == ShadowOperation.UNLINK_AND_TOMBSTONE) { - @SuppressWarnings("unchecked") ObjectDelta markAsDead = deltaFor(ShadowType.class) .item(ShadowType.F_DEAD).replace(Boolean.TRUE) .item(ShadowType.F_EXISTS).replace(Boolean.FALSE) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java index f7a5873256f..af8ee29620d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestDeputy.java @@ -7,7 +7,6 @@ package com.evolveum.midpoint.model.intest; import java.io.File; - import javax.xml.datatype.XMLGregorianCalendar; import org.springframework.test.annotation.DirtiesContext; @@ -15,7 +14,6 @@ import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; -import com.evolveum.midpoint.model.intest.sync.TestValidityRecomputeTask; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismTestUtil; @@ -25,21 +23,16 @@ import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * Test for deputy (delegation) mechanism. - * + *

* MID-3472 * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestDeputy extends AbstractInitializedModelIntegrationTest { @@ -52,8 +45,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - PrismObject userJack = getUser(USER_JACK_OID); display("User Jack", userJack); assertNoAssignments(userJack); @@ -73,8 +64,6 @@ public void test000Sanity() throws Exception { */ @Test public void test100AssignDeputyNoBigDeal() throws Exception { - final String TEST_NAME = "test100AssignDeputyNoBigDeal"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -109,8 +98,6 @@ public void test100AssignDeputyNoBigDeal() throws Exception { */ @Test public void test109UnassignDeputyNoBigDeal() throws Exception { - final String TEST_NAME = "test109UnassignDeputyNoBigDeal"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -144,8 +131,6 @@ public void test109UnassignDeputyNoBigDeal() throws Exception { */ @Test public void test110AssignJackPirate() throws Exception { - final String TEST_NAME = "test110AssignJackPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -181,8 +166,6 @@ public void test110AssignJackPirate() throws Exception { */ @Test public void test112AssignDeputyPirate() throws Exception { - final String TEST_NAME = "test112AssignDeputyPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -223,8 +206,6 @@ public void test112AssignDeputyPirate() throws Exception { */ @Test public void test119UnassignDeputyPirate() throws Exception { - final String TEST_NAME = "test119UnassignDeputyPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -260,8 +241,6 @@ public void test119UnassignDeputyPirate() throws Exception { */ @Test public void test120AssignbarbossaDeputyOfGuybrush() throws Exception { - final String TEST_NAME = "test120AssignbarbossaDeputyOfGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -302,8 +281,6 @@ public void test120AssignbarbossaDeputyOfGuybrush() throws Exception { */ @Test public void test122AssignGuybrushPirate() throws Exception { - final String TEST_NAME = "test122AssignGuybrushPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -340,8 +317,6 @@ public void test122AssignGuybrushPirate() throws Exception { */ @Test public void test124RecomputeBarbossa() throws Exception { - final String TEST_NAME = "test124RecomputeBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -380,8 +355,6 @@ public void test124RecomputeBarbossa() throws Exception { */ @Test public void test126UnassignGuybrushPirate() throws Exception { - final String TEST_NAME = "test126UnassignGuybrushPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -417,8 +390,6 @@ public void test126UnassignGuybrushPirate() throws Exception { */ @Test public void test128RecomputeBarbossa() throws Exception { - final String TEST_NAME = "test128RecomputeBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -450,8 +421,6 @@ public void test128RecomputeBarbossa() throws Exception { @Test public void test129UnassignBarbossaDeputyOfGuybrush() throws Exception { - final String TEST_NAME = "test129UnassignBarbossaDeputyOfGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -485,26 +454,24 @@ public void test129UnassignBarbossaDeputyOfGuybrush() throws Exception { */ @Test public void test150AssignJackMoreRoles() throws Exception { - final String TEST_NAME = "test150AssignJackMoreRoles"; - Task task = getTestTask(); OperationResult result = task.getResult(); - ObjectDelta userDelta = createAssignmentUserDelta(USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, - null, null, (ActivationType) null, true); + ObjectDelta userDelta = createAssignmentUserDelta( + USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); // Captain is NOT delegable - userDelta.addModification((createAssignmentModification(ROLE_CAPTAIN_OID, RoleType.COMPLEX_TYPE, - null, null, (ActivationType) null, true))); - userDelta.addModification((createAssignmentModification(ROLE_RED_SAILOR_OID, RoleType.COMPLEX_TYPE, - null, null, (ActivationType) null, true))); - userDelta.addModification((createAssignmentModification(ROLE_CYAN_SAILOR_OID, RoleType.COMPLEX_TYPE, - null, null, (ActivationType) null, true))); - userDelta.addModification((createAssignmentModification(ORG_SWASHBUCKLER_SECTION_OID, OrgType.COMPLEX_TYPE, - null, null, (ActivationType) null, true))); - userDelta.addModification((createAssignmentModification(ORG_MINISTRY_OF_RUM_OID, OrgType.COMPLEX_TYPE, - SchemaConstants.ORG_MANAGER, null, (ActivationType) null, true))); - userDelta.addModification((createAssignmentModification(ROLE_EMPTY_OID, RoleType.COMPLEX_TYPE, - null, null, (ActivationType) null, true))); + userDelta.addModification((createAssignmentModification(ROLE_CAPTAIN_OID, + RoleType.COMPLEX_TYPE, null, null, null, true))); + userDelta.addModification((createAssignmentModification(ROLE_RED_SAILOR_OID, + RoleType.COMPLEX_TYPE, null, null, null, true))); + userDelta.addModification((createAssignmentModification(ROLE_CYAN_SAILOR_OID, + RoleType.COMPLEX_TYPE, null, null, null, true))); + userDelta.addModification((createAssignmentModification(ORG_SWASHBUCKLER_SECTION_OID, + OrgType.COMPLEX_TYPE, null, null, null, true))); + userDelta.addModification((createAssignmentModification(ORG_MINISTRY_OF_RUM_OID, + OrgType.COMPLEX_TYPE, SchemaConstants.ORG_MANAGER, null, null, true))); + userDelta.addModification((createAssignmentModification(ROLE_EMPTY_OID, + RoleType.COMPLEX_TYPE, null, null, null, true))); // WHEN when(); @@ -538,8 +505,6 @@ public void test150AssignJackMoreRoles() throws Exception { @Test public void test152AssignbarbossaDeputyLimitedDeputy() throws Exception { - final String TEST_NAME = "test152AssignbarbossaDeputyLimitedDeputy"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -574,8 +539,6 @@ public void test152AssignbarbossaDeputyLimitedDeputy() throws Exception { @Test public void test154UnassignbarbossaDeputyLimitedDeputy() throws Exception { - final String TEST_NAME = "test154UnassignbarbossaDeputyLimitedDeputy"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -607,8 +570,6 @@ public void test154UnassignbarbossaDeputyLimitedDeputy() throws Exception { @Test public void test156AssignbarbossaDeputyLimitedDeputyRed() throws Exception { - final String TEST_NAME = "test156AssignbarbossaDeputyLimitedDeputyRed"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -644,8 +605,6 @@ public void test156AssignbarbossaDeputyLimitedDeputyRed() throws Exception { @Test public void test159UnassignbarbossaDeputyLimitedDeputyRed() throws Exception { - final String TEST_NAME = "test159UnassignbarbossaDeputyLimitedDeputyRed"; - Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -657,8 +616,7 @@ public void test159UnassignbarbossaDeputyLimitedDeputyRed() throws Exception { unassignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, createRoleReference(ROLE_RED_SAILOR_OID), - createOrgReference(ORG_MINISTRY_OF_RUM_OID) // There is no assignment like this in Jack - ); + createOrgReference(ORG_MINISTRY_OF_RUM_OID)); // There is no assignment like this in Jack // THEN then(); @@ -680,13 +638,10 @@ public void test159UnassignbarbossaDeputyLimitedDeputyRed() throws Exception { assertAssignments(userJackAfter, 7); assertLinks(userJackAfter, 3); assertAuthorizations(userJackAfter, AUTZ_LOOT_URL, AUTZ_SAIL_URL, AUTZ_SAIL_URL, AUTZ_COMMAND_URL); - } @Test public void test160AssignbarbossaDeputyLimitedDeputyEmpty() throws Exception { - final String TEST_NAME = "test160AssignbarbossaDeputyLimitedDeputyEmpty"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -694,8 +649,7 @@ public void test160AssignbarbossaDeputyLimitedDeputyEmpty() throws Exception { when(); assignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, - createRoleReference(ROLE_EMPTY_OID) - ); + createRoleReference(ROLE_EMPTY_OID)); // THEN then(); @@ -721,8 +675,6 @@ public void test160AssignbarbossaDeputyLimitedDeputyEmpty() throws Exception { @Test public void test162UnassignbarbossaDeputyLimitedDeputyEmpty() throws Exception { - final String TEST_NAME = "test162UnassignbarbossaDeputyLimitedDeputyEmpty"; - Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -733,8 +685,7 @@ public void test162UnassignbarbossaDeputyLimitedDeputyEmpty() throws Exception { when(); unassignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, - createRoleReference(ROLE_EMPTY_OID) - ); + createRoleReference(ROLE_EMPTY_OID)); // THEN then(); @@ -760,8 +711,6 @@ public void test162UnassignbarbossaDeputyLimitedDeputyEmpty() throws Exception { @Test public void test170AddRoleDrinker() throws Exception { - final String TEST_NAME = "test170AssignJackRoleDrinker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -784,8 +733,6 @@ public void test170AddRoleDrinker() throws Exception { @Test public void test172AssignJackRoleDrinker() throws Exception { - final String TEST_NAME = "test170AssignJackRoleDrinker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -813,8 +760,6 @@ public void test172AssignJackRoleDrinker() throws Exception { @Test public void test174AssignBarbossaDeputyLimitedDeputyDrinker() throws Exception { - final String TEST_NAME = "test174AssignBarbossaDeputyLimitedDeputyDrinker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -822,8 +767,7 @@ public void test174AssignBarbossaDeputyLimitedDeputyDrinker() throws Exception { when(); assignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, - createRoleReference(ROLE_DRINKER_OID) - ); + createRoleReference(ROLE_DRINKER_OID)); // THEN then(); @@ -851,8 +795,6 @@ public void test174AssignBarbossaDeputyLimitedDeputyDrinker() throws Exception { */ @Test public void test176AssignbarGuybrushLimitedDeputyOfBarbossa() throws Exception { - final String TEST_NAME = "test176AssignbarGuybrushLimitedDeputyOfBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -863,15 +805,13 @@ public void test176AssignbarGuybrushLimitedDeputyOfBarbossa() throws Exception { assertLinks(userGuybrushBefore, 0); assertNoAuthorizations(userGuybrushBefore); - // WHEN when(); assignDeputyLimits(USER_GUYBRUSH_OID, USER_BARBOSSA_OID, assignment -> assignment.beginLimitTargetContent().allowTransitive(true), task, result, - createRoleReference(ROLE_DRINKER_OID) - ); + createRoleReference(ROLE_DRINKER_OID)); // THEN then(); @@ -888,8 +828,6 @@ public void test176AssignbarGuybrushLimitedDeputyOfBarbossa() throws Exception { @Test public void test178UnassignBarbossaDeputyLimitedDeputyDrinker() throws Exception { - final String TEST_NAME = "test178UnassignBsarbossaDeputyLimitedDeputyDrinker"; - Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -900,8 +838,7 @@ public void test178UnassignBarbossaDeputyLimitedDeputyDrinker() throws Exception when(); unassignDeputyLimits(USER_BARBOSSA_OID, USER_JACK_OID, task, result, - createRoleReference(ROLE_DRINKER_OID) - ); + createRoleReference(ROLE_DRINKER_OID)); // THEN then(); @@ -934,8 +871,6 @@ public void test178UnassignBarbossaDeputyLimitedDeputyDrinker() throws Exception @Test public void test179UnassignbarGuybrushLimitedDeputyOfBarbossa() throws Exception { - final String TEST_NAME = "test179UnassignbarGuybrushLimitedDeputyOfBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -945,8 +880,7 @@ public void test179UnassignbarGuybrushLimitedDeputyOfBarbossa() throws Exception unassignDeputyLimits(USER_GUYBRUSH_OID, USER_BARBOSSA_OID, assignment -> assignment.beginLimitTargetContent().allowTransitive(true), task, result, - createRoleReference(ROLE_DRINKER_OID) - ); + createRoleReference(ROLE_DRINKER_OID)); // THEN then(); @@ -962,8 +896,6 @@ public void test179UnassignbarGuybrushLimitedDeputyOfBarbossa() throws Exception @Test public void test180AssignBarbossaDeputyOfJack() throws Exception { - final String TEST_NAME = "test180AssignBarbossaDeputyOfJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -990,8 +922,6 @@ public void test180AssignBarbossaDeputyOfJack() throws Exception { */ @Test public void test182AssignGuybrushLimitedDeputyOfBarbossa() throws Exception { - final String TEST_NAME = "test182AssignGuybrushLimitedDeputyOfBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1002,7 +932,6 @@ public void test182AssignGuybrushLimitedDeputyOfBarbossa() throws Exception { assertLinks(userGuybrushBefore, 0); assertNoAuthorizations(userGuybrushBefore); - // WHEN when(); @@ -1025,8 +954,6 @@ public void test182AssignGuybrushLimitedDeputyOfBarbossa() throws Exception { @Test public void test184UnassignGuybrushLimitedDeputyOfBarbossa() throws Exception { - final String TEST_NAME = "test182AssignGuybrushLimitedDeputyOfBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1053,8 +980,6 @@ public void test184UnassignGuybrushLimitedDeputyOfBarbossa() throws Exception { */ @Test public void test186AssignGuybrushDeputyOfBarbossa() throws Exception { - final String TEST_NAME = "test182AssignGuybrushLimitedDeputyOfBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1065,7 +990,6 @@ public void test186AssignGuybrushDeputyOfBarbossa() throws Exception { assertLinks(userGuybrushBefore, 0); assertNoAuthorizations(userGuybrushBefore); - // WHEN when(); @@ -1086,8 +1010,6 @@ public void test186AssignGuybrushDeputyOfBarbossa() throws Exception { @Test public void test188UnassignGuybrushDeputyOfBarbossa() throws Exception { - final String TEST_NAME = "test188UnassignGuybrushDeputyOfBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1109,8 +1031,6 @@ public void test188UnassignGuybrushDeputyOfBarbossa() throws Exception { @Test public void test189UnassignBarbossaDeputyOfJack() throws Exception { - final String TEST_NAME = "test189UnassignBarbossaDeputyOfJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1132,8 +1052,6 @@ public void test189UnassignBarbossaDeputyOfJack() throws Exception { @Test public void test190AssignBarbossaDeputyLimitedDeputyEmptyDrinker() throws Exception { - final String TEST_NAME = "test190AssignBarbossaDeputyLimitedDeputyEmptyDrinker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1169,8 +1087,6 @@ public void test190AssignBarbossaDeputyLimitedDeputyEmptyDrinker() throws Except @Test public void test192UnassignbarbossaDeputyLimitedDeputyEmptyDrinker() throws Exception { - final String TEST_NAME = "test192UnassignbarbossaDeputyLimitedDeputyEmptyDrinker"; - Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); @@ -1207,15 +1123,9 @@ public void test192UnassignbarbossaDeputyLimitedDeputyEmptyDrinker() throws Exce } - @Test public void test800ImportValidityScannerTask() throws Exception { - final String TEST_NAME = "test800ImportValidityScannerTask"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); /// WHEN @@ -1237,8 +1147,6 @@ public void test800ImportValidityScannerTask() throws Exception { */ @Test public void test802AssignBarbossaDeputyOfJack() throws Exception { - final String TEST_NAME = "test802AssignBarbossaDeputyOfJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1263,8 +1171,6 @@ public void test802AssignBarbossaDeputyOfJack() throws Exception { then(); assertSuccess(result); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); @@ -1290,15 +1196,11 @@ public void test802AssignBarbossaDeputyOfJack() throws Exception { */ @Test public void test804BarbosaThreeHoursLater() throws Exception { - final String TEST_NAME = "test804BarbosaThreeHoursLater"; - Task task = getTestTask(); OperationResult result = task.getResult(); clock.overrideDuration("PT3H"); - XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); @@ -1308,8 +1210,6 @@ public void test804BarbosaThreeHoursLater() throws Exception { then(); assertSuccess(result); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - PrismObject userBarbossaAfter = getUser(USER_BARBOSSA_OID); display("User Barbossa after", userBarbossaAfter); assertAssignedDeputy(userBarbossaAfter, USER_JACK_OID); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestEntitlements.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestEntitlements.java index e55a004f50a..45a25716e07 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestEntitlements.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestEntitlements.java @@ -6,6 +6,23 @@ */ package com.evolveum.midpoint.model.intest; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.io.FileNotFoundException; +import java.net.ConnectException; +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.icf.dummy.resource.*; import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; import com.evolveum.midpoint.prism.PrismObject; @@ -30,30 +47,13 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import java.io.File; -import java.io.FileNotFoundException; -import java.net.ConnectException; -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; /** * Test of account-entitlement association. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestEntitlements extends AbstractInitializedModelIntegrationTest { @@ -144,8 +144,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100AddGroupShadowSwashbucklers() throws Exception { - final String TEST_NAME = "test100AddGroupShadowSwashbucklers"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -172,8 +170,6 @@ public void test100AddGroupShadowSwashbucklers() throws Exception { @Test public void test101GetGroupShadowSwashbucklers() throws Exception { - final String TEST_NAME = "test101GetGroupShadowSwashbucklers"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -194,8 +190,6 @@ public void test101GetGroupShadowSwashbucklers() throws Exception { */ @Test public void test110AssociateGuybrushToSwashbucklers() throws Exception { - final String TEST_NAME = "test110AssociateGuybrushToSwashbucklers"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -212,14 +206,12 @@ public void test110AssociateGuybrushToSwashbucklers() throws Exception { assertSuccess(result); assertDummyGroupByName(null, GROUP_DUMMY_SWASHBUCKLERS_NAME) - .assertDescription(GROUP_DUMMY_SWASHBUCKLERS_DESCRIPTION) - .assertMember(ACCOUNT_GUYBRUSH_DUMMY_USERNAME); + .assertDescription(GROUP_DUMMY_SWASHBUCKLERS_DESCRIPTION) + .assertMember(ACCOUNT_GUYBRUSH_DUMMY_USERNAME); } @Test public void test200AssignRoleSwashbucklerToJack() throws Exception { - final String TEST_NAME = "test200AssignRoleSwashbucklerToJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -248,8 +240,6 @@ public void test200AssignRoleSwashbucklerToJack() throws Exception { @Test public void test209UnAssignRoleSwashbucklerFromJack() throws Exception { - final String TEST_NAME = "test209UnAssignRoleSwashbucklerFromJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -281,8 +271,6 @@ public void test209UnAssignRoleSwashbucklerFromJack() throws Exception { */ @Test public void test220AssignRoleLandluberToWally() throws Exception { - final String TEST_NAME = "test220AssignRoleLandluberToWally"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -310,8 +298,6 @@ public void test220AssignRoleLandluberToWally() throws Exception { */ @Test public void test222AssignRoleMapmakerToWally() throws Exception { - final String TEST_NAME = "test222AssignRoleMapmakerToWally"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -340,20 +326,18 @@ public void test222AssignRoleMapmakerToWally() throws Exception { .assertKind(ShadowKindType.UNKNOWN); String accountWallyOid = assertUserAfterByUsername(USER_WALLY_NAME) - .singleLink() + .singleLink() .getOid(); assertModelShadow(accountWallyOid) - .associations() + .associations() .assertSize(2) .association(RESOURCE_DUMMY_ASSOCIATION_GROUP_QNAME) - .assertShadowOids(groupLandlubersShadow.getOid(), groupMapmakersShadow.getOid()); + .assertShadowOids(groupLandlubersShadow.getOid(), groupMapmakersShadow.getOid()); } @Test public void test224UnassignRoleMapmakerFromWally() throws Exception { - final String TEST_NAME = "test224UnassignRoleMapmakerFromWally"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -373,11 +357,8 @@ public void test224UnassignRoleMapmakerFromWally() throws Exception { assertNoGroupMember(dummyGroup, USER_WALLY_NAME); } - @Test public void test300AddRoleWimp() throws Exception { - final String TEST_NAME = "test300AddRoleWimp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -408,8 +389,6 @@ public void test300AddRoleWimp() throws Exception { @Test public void test302AddRoleBrute() throws Exception { - final String TEST_NAME = "test302AddRoleBrute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -435,8 +414,6 @@ public void test302AddRoleBrute() throws Exception { @Test public void test304AddRoleThug() throws Exception { - final String TEST_NAME = "test304AddRoleThug"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -462,8 +439,6 @@ public void test304AddRoleThug() throws Exception { @Test public void test310AssignRoleWimpToLargo() throws Exception { - final String TEST_NAME = "test310AssignRoleWimpToLargo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -488,8 +463,6 @@ public void test310AssignRoleWimpToLargo() throws Exception { @Test public void test312AssignRoleBruteToLargo() throws Exception { - final String TEST_NAME = "test312AssignRoleBruteToLargo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -512,8 +485,6 @@ public void test312AssignRoleBruteToLargo() throws Exception { @Test public void test313UnAssignRoleBruteFromLargo() throws Exception { - final String TEST_NAME = "test313UnAssignRoleBruteFromLargo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -546,8 +517,6 @@ public void test313UnAssignRoleBruteFromLargo() throws Exception { @Test public void test314AssignRoleThugToLargo() throws Exception { - final String TEST_NAME = "test314AssignRoleThugToLargo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -570,8 +539,6 @@ public void test314AssignRoleThugToLargo() throws Exception { @Test public void test315UnAssignRoleThugFromLargo() throws Exception { - final String TEST_NAME = "test315UnAssignRoleThugFromLargo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -607,8 +574,6 @@ public void test315UnAssignRoleThugFromLargo() throws Exception { */ @Test public void test317RenameLargo() throws Exception { - final String TEST_NAME = "test317RenameLargo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -638,8 +603,6 @@ public void test317RenameLargo() throws Exception { @Test public void test319UnassignRoleWimpFromLargo() throws Exception { - final String TEST_NAME = "test319UnassignRoleWimpFromLargo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -674,8 +637,6 @@ public void test319UnassignRoleWimpFromLargo() throws Exception { */ @Test public void test320AssignRoleBruteToRapp() throws Exception { - final String TEST_NAME = "test320AssignRoleBruteToRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -700,8 +661,6 @@ public void test320AssignRoleBruteToRapp() throws Exception { @Test public void test322AssignRoleWimpToRapp() throws Exception { - final String TEST_NAME = "test322AssignRoleWimpToRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -731,8 +690,6 @@ public void test322AssignRoleWimpToRapp() throws Exception { @Test public void test324AssignRoleThugToRapp() throws Exception { - final String TEST_NAME = "test324AssignRoleThugToRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -769,8 +726,6 @@ public void test324AssignRoleThugToRapp() throws Exception { @Test public void test327UnassignRoleWimpFromRapp() throws Exception { - final String TEST_NAME = "test327UnassignRoleWimpFromRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -810,8 +765,6 @@ public void test327UnassignRoleWimpFromRapp() throws Exception { @Test public void test328UnassignRoleThugFromRapp() throws Exception { - final String TEST_NAME = "test328UnassignRoleThugFromRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -854,8 +807,6 @@ public void test328UnassignRoleThugFromRapp() throws Exception { @Test public void test329UnAssignRoleBruteFromRapp() throws Exception { - final String TEST_NAME = "test329UnAssignRoleBruteFromRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -892,8 +843,6 @@ public void test329UnAssignRoleBruteFromRapp() throws Exception { @Test public void test350AssignOrangeAccountToGuybrushAndRapp() throws Exception { - final String TEST_NAME = "test350AssignOrangeAccountToGuybrushAndRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -917,8 +866,6 @@ public void test350AssignOrangeAccountToGuybrushAndRapp() throws Exception { */ @Test public void test351AssignRoleCrewOfGuybrushToRapp() throws Exception { - final String TEST_NAME = "test351AssignRoleCrewOfGuybrushToRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -961,8 +908,6 @@ public void test351AssignRoleCrewOfGuybrushToRapp() throws Exception { */ @Test public void test358UnassignRoleCrewOfGuybrushToRapp() throws Exception { - final String TEST_NAME = "test358UnassignRoleCrewOfGuybrushToRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1000,8 +945,6 @@ public void test358UnassignRoleCrewOfGuybrushToRapp() throws Exception { @Test public void test359UnassignOrangeAccountFromGuybrushAndRapp() throws Exception { - final String TEST_NAME = "test359UnassignOrangeAccountFromGuybrushAndRapp"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1022,8 +965,6 @@ public void test359UnassignOrangeAccountFromGuybrushAndRapp() throws Exception { @Test public void test600AssignRolePirateToJack() throws Exception { - final String TEST_NAME = "test600AssignRolePirateToJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1049,15 +990,12 @@ public void test600AssignRolePirateToJack() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Bloody Pirate"); } @Test public void test610AssignRoleSwashbucklerToJack() throws Exception { - final String TEST_NAME = "test610AssignRoleSwashbucklerToJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1089,8 +1027,6 @@ public void test610AssignRoleSwashbucklerToJack() throws Exception { @Test public void test620UnAssignSwashbucklerFromJack() throws Exception { - final String TEST_NAME = "test620UnAssignSwashbucklerFromJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1116,7 +1052,6 @@ public void test620UnAssignSwashbucklerFromJack() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Bloody Pirate"); } @@ -1126,19 +1061,17 @@ public void test620UnAssignSwashbucklerFromJack() throws Exception { */ @Test public void test630AssignRoleSwashbucklerToJackValidity() throws Exception { - final String TEST_NAME = "test630AssignRoleSwashbucklerToJackValidity"; - Task task = getTestTask(); OperationResult result = task.getResult(); jackSwashbucklerAssignmentActivation = new ActivationType(); XMLGregorianCalendar validFrom = clock.currentTimeXMLGregorianCalendar(); - validFrom.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead + validFrom.add(XmlTypeConverter.createDuration(60 * 60 * 1000)); // one hour ahead jackSwashbucklerAssignmentActivation.setValidFrom(validFrom); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(3*60*60*1000)); // three hours ahead + validTo.add(XmlTypeConverter.createDuration(3 * 60 * 60 * 1000)); // three hours ahead jackSwashbucklerAssignmentActivation.setValidTo(validTo); // WHEN @@ -1169,8 +1102,6 @@ public void test630AssignRoleSwashbucklerToJackValidity() throws Exception { @Test public void test640JackRoleSwashbucklerBecomesValid() throws Exception { - final String TEST_NAME = "test640JackRoleSwashbucklerBecomesValid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1197,15 +1128,12 @@ public void test640JackRoleSwashbucklerBecomesValid() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, "grog"); - assertDummyAccountAttribute(null, ACCOUNT_JACK_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Bloody Pirate", "Swashbuckler"); } @Test public void test645JackRoleSwashbucklerIsValid() throws Exception { - final String TEST_NAME = "test645JackRoleSwashbucklerIsValid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1235,8 +1163,6 @@ public void test645JackRoleSwashbucklerIsValid() throws Exception { @Test public void test650JackRoleSwashbucklerBecomesInvalid() throws Exception { - final String TEST_NAME = "test650JackRoleSwashbucklerBecomesInvalid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1270,8 +1196,6 @@ public void test650JackRoleSwashbucklerBecomesInvalid() throws Exception { @Test public void test659UnassignRoleSwashbucklerFromJack() throws Exception { - final String TEST_NAME = "test659UnassignRoleSwashbucklerFromJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1309,8 +1233,6 @@ public void test659UnassignRoleSwashbucklerFromJack() throws Exception { @Test public void test699UnassignRolePirateFromJack() throws Exception { - final String TEST_NAME = "test699UnassignRolePirateFromJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1334,8 +1256,6 @@ public void test699UnassignRolePirateFromJack() throws Exception { */ @Test public void test700ReconcileGuybrush() throws Exception { - final String TEST_NAME = "test700ReconcileGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); clock.resetOverride(); @@ -1367,15 +1287,13 @@ public void test700ReconcileGuybrush() throws Exception { */ @Test public void test710AssociateGuybrushToLandlubers() throws Exception { - final String TEST_NAME = "test710AssociateGuybrushToLandlubers"; - Task task = getTestTask(); OperationResult result = task.getResult(); ObjectDelta delta = IntegrationTestTools.createEntitleDelta(ACCOUNT_SHADOW_GUYBRUSH_OID, - dummyResourceCtl.getAttributeQName(DummyResourceContoller.DUMMY_ENTITLEMENT_GROUP_NAME), - SHADOW_GROUP_DUMMY_LANDLUBERS_OID, prismContext); + dummyResourceCtl.getAttributeQName(DummyResourceContoller.DUMMY_ENTITLEMENT_GROUP_NAME), + SHADOW_GROUP_DUMMY_LANDLUBERS_OID, prismContext); // WHEN executeChanges(delta, null, task, result); @@ -1386,14 +1304,11 @@ public void test710AssociateGuybrushToLandlubers() throws Exception { assertGroupMember(GROUP_DUMMY_LANDLUBERS_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, getDummyResource()); } - /** * Add account to 2 groups using model service (shadow operations) - preparation for next test (intolerantValuePatterns) */ @Test public void test715AssociateGuybrushToThugs() throws Exception { - final String TEST_NAME = "test715AssociateGuybrushToThugs"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1408,13 +1323,13 @@ public void test715AssociateGuybrushToThugs() throws Exception { IntegrationTestTools.createEntitleDelta(orangeAccount.getOid(), getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributeQName(DummyResourceContoller.DUMMY_ENTITLEMENT_GROUP_NAME), getGroupShadow(getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME), getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getGroupObjectClass(), "thug", task, result).getOid(), - prismContext); + prismContext); ObjectDelta delta2 = IntegrationTestTools.createEntitleDelta(orangeAccount.getOid(), getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getAttributeQName(DummyResourceContoller.DUMMY_ENTITLEMENT_GROUP_NAME), - getGroupShadow(getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME), getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getGroupObjectClass(), "thug-wannabe", task, result) .getOid(), - prismContext); + getGroupShadow(getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME), getDummyResourceController(RESOURCE_DUMMY_ORANGE_NAME).getGroupObjectClass(), "thug-wannabe", task, result).getOid(), + prismContext); ObjectDelta delta = ObjectDeltaCollectionsUtil.summarize(delta1, delta2); @@ -1427,7 +1342,7 @@ public void test715AssociateGuybrushToThugs() throws Exception { assertSuccess(result); assertGroupMember(GROUP_THUG_NAME, ACCOUNT_GUYBRUSH_DUMMY_ORANGE_USERNAME, getDummyResource(RESOURCE_DUMMY_ORANGE_NAME)); - assertGroupMember(GROUP_THUG_NAME+"-wannabe", ACCOUNT_GUYBRUSH_DUMMY_ORANGE_USERNAME, getDummyResource(RESOURCE_DUMMY_ORANGE_NAME)); + assertGroupMember(GROUP_THUG_NAME + "-wannabe", ACCOUNT_GUYBRUSH_DUMMY_ORANGE_USERNAME, getDummyResource(RESOURCE_DUMMY_ORANGE_NAME)); } /** @@ -1435,8 +1350,6 @@ public void test715AssociateGuybrushToThugs() throws Exception { */ @Test public void test720ReconcileGuybrush() throws Exception { - final String TEST_NAME = "test720ReconcileGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1455,13 +1368,11 @@ public void test720ReconcileGuybrush() throws Exception { dumpUserAndAccounts(getUser(USER_GUYBRUSH_OID), task, result); assertGroupMember(GROUP_DUMMY_LANDLUBERS_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, getDummyResource()); assertGroupMember(GROUP_THUG_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, getDummyResource(RESOURCE_DUMMY_ORANGE_NAME)); - assertNoGroupMember(GROUP_THUG_NAME+"-wannabe", ACCOUNT_GUYBRUSH_DUMMY_USERNAME, getDummyResource(RESOURCE_DUMMY_ORANGE_NAME)); + assertNoGroupMember(GROUP_THUG_NAME + "-wannabe", ACCOUNT_GUYBRUSH_DUMMY_USERNAME, getDummyResource(RESOURCE_DUMMY_ORANGE_NAME)); } @Test public void test729CleanupGuybrush() throws Exception { - final String TEST_NAME = "test729CleanupGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1491,8 +1402,6 @@ public void test729CleanupGuybrush() throws Exception { */ @Test public void test750PrepareGuybrushFuturePerfect() throws Exception { - final String TEST_NAME = "test750PrepareGuybrushFuturePerfect"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1533,8 +1442,6 @@ private String orgGroupName(String ou) { */ @Test public void test752GuybrushFuturePerfect() throws Exception { - final String TEST_NAME = "test752GuybrushFuturePerfect"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1558,8 +1465,6 @@ public void test752GuybrushFuturePerfect() throws Exception { @Test public void test759CleanupGuybrush() throws Exception { - final String TEST_NAME = "test759CleanupGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1584,8 +1489,6 @@ public void test759CleanupGuybrush() throws Exception { */ @Test public void test760GuybrushOrgGroupsRepo() throws Exception { - final String TEST_NAME = "test760GuybrushOrgGroupsRepo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1611,8 +1514,6 @@ public void test760GuybrushOrgGroupsRepo() throws Exception { @Test public void test765ReconcileGuybrush() throws Exception { - final String TEST_NAME = "test765ReconcileGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); @@ -1642,8 +1543,6 @@ public void test765ReconcileGuybrush() throws Exception { @Test public void test769CleanupGuybrush() throws Exception { - final String TEST_NAME = "test769CleanupGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1668,8 +1567,6 @@ public void test769CleanupGuybrush() throws Exception { */ @Test public void test780AssignGuybrushSwashbuckler() throws Exception { - final String TEST_NAME = "test780AssignGuybrushSwashbuckler"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1692,8 +1589,6 @@ public void test780AssignGuybrushSwashbuckler() throws Exception { */ @Test public void test781GuybrushTheLostSwashbuckler() throws Exception { - final String TEST_NAME = "test781GuybrushTheLostSwashbuckler"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1715,8 +1610,6 @@ public void test781GuybrushTheLostSwashbuckler() throws Exception { @Test public void test784UnassignGuybrushSwashbuckler() throws Exception { - final String TEST_NAME = "test784UnassignGuybrushSwashbuckler"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1734,8 +1627,6 @@ public void test784UnassignGuybrushSwashbuckler() throws Exception { @Test public void test785AssignGuybrushBlueSwashbuckler() throws Exception { - final String TEST_NAME = "test785AssignGuybrushBlueSwashbuckler"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1761,8 +1652,6 @@ public void test785AssignGuybrushBlueSwashbuckler() throws Exception { */ @Test public void test786GuybrushTheLostBlueSwashbuckler() throws Exception { - final String TEST_NAME = "test786GuybrushTheLostBlueSwashbuckler"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1784,8 +1673,6 @@ public void test786GuybrushTheLostBlueSwashbuckler() throws Exception { @Test public void test789UnassignGuybrushBlueSwashbuckler() throws Exception { - final String TEST_NAME = "test789UnassignGuybrushBlueSwashbuckler"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1806,8 +1693,6 @@ public void test789UnassignGuybrushBlueSwashbuckler() throws Exception { */ @Test public void test800AssignRoleSwashbucklerToJackNone() throws Exception { - final String TEST_NAME = "test800AssignRoleSwashbucklerToJackNone"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1839,8 +1724,6 @@ public void test800AssignRoleSwashbucklerToJackNone() throws Exception { */ @Test public void test805ReconcileJackNone() throws Exception { - final String TEST_NAME = "test805ReconcileJackNone"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1867,8 +1750,6 @@ public void test805ReconcileJackNone() throws Exception { */ @Test public void test809UnAssignRoleSwashbucklerFromJackNone() throws Exception { - final String TEST_NAME = "test809UnAssignRoleSwashbucklerFromJackNone"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1894,8 +1775,6 @@ public void test809UnAssignRoleSwashbucklerFromJackNone() throws Exception { */ @Test public void test810AssignRoleSwashbucklerToJackPositive() throws Exception { - final String TEST_NAME = "test810AssignRoleSwashbucklerToJackPositive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1925,8 +1804,6 @@ public void test810AssignRoleSwashbucklerToJackPositive() throws Exception { */ @Test public void test815ReconcileJackPositive() throws Exception { - final String TEST_NAME = "test815ReconcileJackPositive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1953,8 +1830,6 @@ public void test815ReconcileJackPositive() throws Exception { */ @Test public void test817UnAssignRoleSwashbucklerFromJackPositive() throws Exception { - final String TEST_NAME = "test817UnAssignRoleSwashbucklerFromJackPositive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1980,8 +1855,6 @@ public void test817UnAssignRoleSwashbucklerFromJackPositive() throws Exception { */ @Test public void test819ReconcileJackPositive() throws Exception { - final String TEST_NAME = "test819ReconcileJackPositive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2012,8 +1885,6 @@ public void test819ReconcileJackPositive() throws Exception { */ @Test public void test820RecomputeJackFull() throws Exception { - final String TEST_NAME = "test820RecomputeJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2042,8 +1913,6 @@ public void test820RecomputeJackFull() throws Exception { */ @Test public void test822AssignRoleSwashbucklerToJackFull() throws Exception { - final String TEST_NAME = "test822AssignRoleSwashbucklerToJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2073,8 +1942,6 @@ public void test822AssignRoleSwashbucklerToJackFull() throws Exception { */ @Test public void test825ReconcileJackFull() throws Exception { - final String TEST_NAME = "test825ReconcileJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2101,8 +1968,6 @@ public void test825ReconcileJackFull() throws Exception { */ @Test public void test827UnAssignRoleSwashbucklerFromJackFull() throws Exception { - final String TEST_NAME = "test827UnAssignRoleSwashbucklerFromJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2128,8 +1993,6 @@ public void test827UnAssignRoleSwashbucklerFromJackFull() throws Exception { */ @Test public void test829ReconcileJackFull() throws Exception { - final String TEST_NAME = "test829ReconcileJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2156,8 +2019,6 @@ public void test829ReconcileJackFull() throws Exception { */ @Test public void test830AssignJackAccountDummy() throws Exception { - final String TEST_NAME = "test830AssignJackAccountDummy"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2179,15 +2040,13 @@ public void test830AssignJackAccountDummy() throws Exception { assertAssignments(userAfter, 1); assertJackAccountNoSwashbuckler(); - } + } /** * MID-4021 */ @Test public void test840AssignRoleSwashbucklerToJackNone() throws Exception { - final String TEST_NAME = "test840AssignRoleSwashbucklerToJackNone"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2217,8 +2076,6 @@ public void test840AssignRoleSwashbucklerToJackNone() throws Exception { */ @Test public void test849UnassignRoleSwashbucklerFromJackNone() throws Exception { - final String TEST_NAME = "test849UnassignRoleSwashbucklerFromJackNone"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2244,8 +2101,6 @@ public void test849UnassignRoleSwashbucklerFromJackNone() throws Exception { */ @Test public void test850AssignRoleSwashbucklerToJackPositive() throws Exception { - final String TEST_NAME = "test850AssignRoleSwashbucklerToJackPositive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2275,8 +2130,6 @@ public void test850AssignRoleSwashbucklerToJackPositive() throws Exception { */ @Test public void test859UnassignRoleSwashbucklerToJackPositive() throws Exception { - final String TEST_NAME = "test859UnassignRoleSwashbucklerToJackPositive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2304,8 +2157,6 @@ public void test859UnassignRoleSwashbucklerToJackPositive() throws Exception { */ @Test public void test860RecomputeJackFull() throws Exception { - final String TEST_NAME = "test860RecomputeJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2331,8 +2182,6 @@ public void test860RecomputeJackFull() throws Exception { */ @Test public void test862AssignRoleSwashbucklerToJackFull() throws Exception { - final String TEST_NAME = "test862AssignRoleSwashbucklerToJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2362,8 +2211,6 @@ public void test862AssignRoleSwashbucklerToJackFull() throws Exception { */ @Test public void test869UnassignRoleSwashbucklerToJackFull() throws Exception { - final String TEST_NAME = "test869UnassignRoleSwashbucklerToJackFull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2389,8 +2236,6 @@ public void test869UnassignRoleSwashbucklerToJackFull() throws Exception { */ @Test public void test899UnAssignAccountJackDummy() throws Exception { - final String TEST_NAME = "test899UnAssignAccountJackDummy"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2445,15 +2290,15 @@ private void assertJackAccountSwashbuckler() throws SchemaViolationException, Co /** * Account: yes, group: no */ - private void assertJackAccountNoSwashbuckler() throws SchemaViolationException, ConflictException, ConnectException, FileNotFoundException, InterruptedException { - assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); - DummyGroup dummyGroup = getDummyResource().getGroupByName(GROUP_DUMMY_SWASHBUCKLERS_NAME); + private void assertJackAccountNoSwashbuckler() throws SchemaViolationException, ConflictException, ConnectException, FileNotFoundException, InterruptedException { + assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); + DummyGroup dummyGroup = getDummyResource().getGroupByName(GROUP_DUMMY_SWASHBUCKLERS_NAME); assertNotNull("No group on dummy resource", dummyGroup); display("Group", dummyGroup); assertEquals("Wrong group description", GROUP_DUMMY_SWASHBUCKLERS_DESCRIPTION, - dummyGroup.getAttributeValue(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION)); + dummyGroup.getAttributeValue(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION)); assertNoGroupMember(dummyGroup, ACCOUNT_JACK_DUMMY_USERNAME); - } + } /** * Account: no, group: no @@ -2478,14 +2323,6 @@ private void dumpUsersAndTheirAccounts(Task task, OperationResult result) throws } } - private void dumpUserAndAccounts(PrismObject user) - throws ConfigurationException, ObjectNotFoundException, SchemaException, CommunicationException, - SecurityViolationException, ExpressionEvaluationException { - Task task = getTestTask(); - OperationResult result = task.getResult(); - dumpUserAndAccounts(user, task, result); - } - private PrismObject dumpUserAndAccounts(String userOid) throws ConfigurationException, ObjectNotFoundException, SchemaException, CommunicationException, SecurityViolationException, ExpressionEvaluationException { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java index 0ac1594591b..c7b63870f1e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java @@ -6,14 +6,13 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNull; import java.io.File; import java.util.ArrayList; import java.util.Collection; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -32,12 +31,13 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author katkav * @author semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestInbounds extends AbstractInitializedModelIntegrationTest { @@ -56,8 +56,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - // GIVEN Task task = getTestTask(); @@ -75,8 +73,6 @@ public void test000Sanity() throws Exception { @Test public void test101ModifyUserSubtypePirate() throws Exception { - final String TEST_NAME = "test101ModifyUserSubtypePirate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -97,19 +93,19 @@ public void test101ModifyUserSubtypePirate() throws Exception { assertSuccess(result); jackEmployeeNumber = assertUserAfter(USER_JACK_OID) - .assertDescription("Where's the rum?") - .assignments() + .assertDescription("Where's the rum?") + .assignments() .single() - .assertRole(ROLE_PIRATE_GREEN_OID) - .metadata() - .assertOriginMappingName("pirate-assignment") - .end() - .end() + .assertRole(ROLE_PIRATE_GREEN_OID) + .metadata() + .assertOriginMappingName("pirate-assignment") .end() - .assertLinks(1) - .assertOrganizationalUnits("The crew of pirate") - .assertEmployeeNumber() - .getObject().asObjectable().getEmployeeNumber(); + .end() + .end() + .assertLinks(1) + .assertOrganizationalUnits("The crew of pirate") + .assertEmployeeNumber() + .getObject().asObjectable().getEmployeeNumber(); } /** @@ -118,8 +114,6 @@ public void test101ModifyUserSubtypePirate() throws Exception { */ @Test public void test102ModifyUserSubtypeBuccaneer() throws Exception { - final String TEST_NAME = "test102ModifyUserSubtypeBuccaneer"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -136,24 +130,22 @@ public void test102ModifyUserSubtypeBuccaneer() throws Exception { assertSuccess(result); assertUserAfter(USER_JACK_OID) - .assertDescription("Where's the rum?") - .assignments() + .assertDescription("Where's the rum?") + .assignments() .single() - .assertRole(ROLE_BUCCANEER_GREEN_OID) - .metadata() - .assertOriginMappingName("buccaneer-assignment") - .end() - .end() + .assertRole(ROLE_BUCCANEER_GREEN_OID) + .metadata() + .assertOriginMappingName("buccaneer-assignment") .end() - .assertLinks(1) - .assertOrganizationalUnits("The crew of buccaneer") - .assertEmployeeNumber(jackEmployeeNumber); + .end() + .end() + .assertLinks(1) + .assertOrganizationalUnits("The crew of buccaneer") + .assertEmployeeNumber(jackEmployeeNumber); } @Test public void test103DeleteUserEmployeeTypeBartender() throws Exception { - final String TEST_NAME = "test103ModifyUserEmployeeTypeBartender"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -192,8 +184,6 @@ public void test103DeleteUserEmployeeTypeBartender() throws Exception { */ @Test public void test200AssignAccountOrange() throws Exception { - final String TEST_NAME = "test200AssignAccountOrange"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -234,8 +224,6 @@ public void test200AssignAccountOrange() throws Exception { */ @Test public void test202ModifyAccountOrangeGossip() throws Exception { - final String TEST_NAME = "test202ModifyAccountOrangeGossip"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -278,8 +266,6 @@ public void test202ModifyAccountOrangeGossip() throws Exception { */ @Test public void test204AssignAccountOrangeAgain() throws Exception { - final String TEST_NAME = "test204AssignAccountOrangeAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -321,8 +307,6 @@ public void test204AssignAccountOrangeAgain() throws Exception { */ @Test public void test209ModifyAccountOrangeGossipRemove() throws Exception { - final String TEST_NAME = "test209ModifyAccountOrangeGossipRemove"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -366,8 +350,6 @@ public void test209ModifyAccountOrangeGossipRemove() throws Exception { */ @Test public void test210ModifyAccountOrangeQuoteMonkey() throws Exception { - final String TEST_NAME = "test210ModifyAccountOrangeQuoteMonkey"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -389,7 +371,7 @@ public void test210ModifyAccountOrangeQuoteMonkey() throws Exception { assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - assertEquals("Wrong description", null, userAfter.asObjectable().getDescription()); + assertNull("Wrong description", userAfter.asObjectable().getDescription()); assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); @@ -416,8 +398,6 @@ public void test210ModifyAccountOrangeQuoteMonkey() throws Exception { */ @Test public void test211ModifyAccountOrangeQuotePirate() throws Exception { - final String TEST_NAME = "test211ModifyAccountOrangeQuotePirate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -466,8 +446,6 @@ public void test211ModifyAccountOrangeQuotePirate() throws Exception { */ @Test public void test214ModifyAccountOrangeQuoteWoodchuck() throws Exception { - final String TEST_NAME = "test214ModifyAccountOrangeQuoteWoodchuck"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -489,7 +467,7 @@ public void test214ModifyAccountOrangeQuoteWoodchuck() throws Exception { assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - assertEquals("Wrong description", null, userAfter.asObjectable().getDescription()); + assertNull("Wrong description", userAfter.asObjectable().getDescription()); assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedNoRole(userAfter); @@ -512,8 +490,6 @@ public void test214ModifyAccountOrangeQuoteWoodchuck() throws Exception { */ @Test public void test250UnlinkAccountDefaultDummy() throws Exception { - final String TEST_NAME = "test250UnlinkAccountDefaultDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -556,8 +532,6 @@ public void test250UnlinkAccountDefaultDummy() throws Exception { */ @Test public void test252ModifyAccountOrangeGossipRecon() throws Exception { - final String TEST_NAME = "test252ModifyAccountOrangeGossipRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -601,8 +575,6 @@ public void test252ModifyAccountOrangeGossipRecon() throws Exception { */ @Test public void test259ModifyAccountOrangeGossipRemoveRecon() throws Exception { - final String TEST_NAME = "test259ModifyAccountOrangeGossipRemoveRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -647,15 +619,13 @@ public void test259ModifyAccountOrangeGossipRemoveRecon() throws Exception { */ @Test public void test260ModifyAccountOrangeQuoteMonkeyRecon() throws Exception { - final String TEST_NAME = "test260ModifyAccountOrangeQuoteMonkeyRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_GUYBRUSH_OID); display("User before", userBefore); - assertEquals("Wrong description", null, userBefore.asObjectable().getDescription()); + assertNull("Wrong description", userBefore.asObjectable().getDescription()); DummyAccount dummyAccountBefore = getDummyAccount(RESOURCE_DUMMY_ORANGE_NAME, USER_GUYBRUSH_USERNAME); dummyAccountBefore.replaceAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, @@ -679,7 +649,7 @@ public void test260ModifyAccountOrangeQuoteMonkeyRecon() throws Exception { assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - assertEquals("Wrong description", null, userAfter.asObjectable().getDescription()); + assertNull("Wrong description", userAfter.asObjectable().getDescription()); assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_THIEF_OID); @@ -701,8 +671,6 @@ public void test260ModifyAccountOrangeQuoteMonkeyRecon() throws Exception { */ @Test public void test261ModifyAccountOrangeQuotePirateRecon() throws Exception { - final String TEST_NAME = "test261ModifyAccountOrangeQuotePirateRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -750,8 +718,6 @@ public void test261ModifyAccountOrangeQuotePirateRecon() throws Exception { */ @Test public void test264ModifyAccountOrangeQuoteWoodchuckRecon() throws Exception { - final String TEST_NAME = "test264ModifyAccountOrangeQuoteWoodchuckRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -777,7 +743,7 @@ public void test264ModifyAccountOrangeQuoteWoodchuckRecon() throws Exception { assertUser(userAfter, USER_GUYBRUSH_OID, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, USER_GUYBRUSH_GIVEN_NAME, USER_GUYBRUSH_FAMILY_NAME); - assertEquals("Wrong description", null, userAfter.asObjectable().getDescription()); + assertNull("Wrong description", userAfter.asObjectable().getDescription()); assertAssignedAccount(userAfter, RESOURCE_DUMMY_ORANGE_OID); assertAssignedRole(userAfter, ROLE_THIEF_OID); @@ -797,8 +763,6 @@ public void test264ModifyAccountOrangeQuoteWoodchuckRecon() throws Exception { */ @Test public void test297ModifyAccountOrangeGossipRecon() throws Exception { - final String TEST_NAME = "test297ModifyAccountOrangeGossipRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -838,8 +802,6 @@ public void test297ModifyAccountOrangeGossipRecon() throws Exception { @Test public void test299UnassignAccountOrange() throws Exception { - final String TEST_NAME = "test299UnassignAccountOrange"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIntent.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIntent.java index e6dc0fc48a9..ac36a94e82d 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIntent.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIntent.java @@ -31,10 +31,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -/** - * @author semancik - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestIntent extends AbstractInitializedModelIntegrationTest { @@ -54,8 +50,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test131ModifyUserJackAssignAccountDefault() throws Exception { - final String TEST_NAME="test131ModifyUserJackAssignAccountDefault"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -113,8 +107,6 @@ public void test131ModifyUserJackAssignAccountDefault() throws Exception { @Test public void test132ModifyUserJackAssignAccountTest() throws Exception { - final String TEST_NAME="test132ModifyUserJackAssignAccountTest"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -185,8 +177,6 @@ public void test132ModifyUserJackAssignAccountTest() throws Exception { @Test public void test135ModifyUserJackFullName() throws Exception { - final String TEST_NAME="test135ModifyUserJackFullName"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -246,8 +236,6 @@ public void test135ModifyUserJackFullName() throws Exception { @Test public void test147ModifyUserJackUnAssignAccountDefault() throws Exception { - final String TEST_NAME="test147ModifyUserJackUnAssignAccountDefault"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -258,8 +246,6 @@ public void test147ModifyUserJackUnAssignAccountDefault() throws Exception { RESOURCE_DUMMY_OID, null, false); deltas.add(accountAssignmentUserDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); modelService.executeChanges(deltas, null, task, result); @@ -267,7 +253,6 @@ public void test147ModifyUserJackUnAssignAccountDefault() throws Exception { // THEN then(); assertSuccess(result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); PrismObject userJack = getUser(USER_JACK_OID); @@ -305,8 +290,6 @@ public void test147ModifyUserJackUnAssignAccountDefault() throws Exception { @Test public void test149ModifyUserJackUnassignAccountTest() throws Exception { - final String TEST_NAME = "test149ModifyUserJackUnassignAccountTest"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIteration.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIteration.java index 06195eb4c2a..cfe2abcc01c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIteration.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestIteration.java @@ -6,34 +6,13 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.schema.SearchResultList; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingStrengthType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceAttributeDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; -import com.evolveum.prism.xml.ns._public.types_3.RawType; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -44,69 +23,57 @@ import com.evolveum.icf.dummy.resource.DummySyncStyle; import com.evolveum.icf.dummy.resource.SchemaViolationException; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.schema.SearchResultList; +import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectTemplateType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +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.ItemPathType; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; +import com.evolveum.prism.xml.ns._public.types_3.RawType; -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestIteration extends AbstractInitializedModelIntegrationTest { public static final File TEST_DIR = new File("src/test/resources/iteration"); - protected static final File USER_XAVIER_FILE = new File(TEST_DIR, "user-xavier.xml"); - protected static final String USER_XAVIER_OID = "c0c010c0-d34d-b33f-f00d-11111111aaa1"; - // Plain iteration, no iteration expressions protected static final File RESOURCE_DUMMY_PINK_FILE = new File(TEST_DIR, "resource-dummy-pink.xml"); protected static final String RESOURCE_DUMMY_PINK_OID = "10000000-0000-0000-0000-00000000a104"; protected static final String RESOURCE_DUMMY_PINK_NAME = "pink"; - protected static final String RESOURCE_DUMMY_PINK_NAMESPACE = MidPointConstants.NS_RI; // Iteration with token expression, pre-iteration condition and post-iteration condition protected static final File RESOURCE_DUMMY_VIOLET_FILE = new File(TEST_DIR, "resource-dummy-violet.xml"); protected static final String RESOURCE_DUMMY_VIOLET_OID = "10000000-0000-0000-0000-00000000a204"; protected static final String RESOURCE_DUMMY_VIOLET_NAME = "violet"; - protected static final String RESOURCE_DUMMY_VIOLET_NAMESPACE = MidPointConstants.NS_RI; // similar to violet but it works in the inbound direction protected static final File RESOURCE_DUMMY_DARK_VIOLET_FILE = new File(TEST_DIR, "resource-dummy-dark-violet.xml"); protected static final String RESOURCE_DUMMY_DARK_VIOLET_OID = "10000000-0000-0000-0000-0000000da204"; protected static final String RESOURCE_DUMMY_DARK_VIOLET_NAME = "darkViolet"; - protected static final String RESOURCE_DUMMY_DARK_VIOLET_NAMESPACE = MidPointConstants.NS_RI; // iteration, token expression, post-iteration condition that invokes isUniquAccountValue() protected static final File RESOURCE_DUMMY_MAGENTA_FILE = new File(TEST_DIR, "resource-dummy-magenta.xml"); protected static final String RESOURCE_DUMMY_MAGENTA_OID = "10000000-0000-0000-0000-00000000a304"; protected static final String RESOURCE_DUMMY_MAGENTA_NAME = "magenta"; - protected static final String RESOURCE_DUMMY_MAGENTA_NAMESPACE = MidPointConstants.NS_RI; // Plain iteration (no expressions). Has synchronization block. protected static final File RESOURCE_DUMMY_FUCHSIA_FILE = new File(TEST_DIR, "resource-dummy-fuchsia.xml"); protected static final String RESOURCE_DUMMY_FUCHSIA_OID = "10000000-0000-0000-0000-0000000dd204"; protected static final String RESOURCE_DUMMY_FUCHSIA_NAME = "fuchsia"; - protected static final String RESOURCE_DUMMY_FUCHSIA_NAMESPACE = MidPointConstants.NS_RI; // Source for "changing template" test (test820) protected static final File RESOURCE_DUMMY_ASSOCIATE_FILE = new File(TEST_DIR, "resource-dummy-associate.xml"); @@ -123,7 +90,6 @@ public class TestIteration extends AbstractInitializedModelIntegrationTest { // Iteration that generates random suffix. Token expression and post- and pre-conditions. protected static final File USER_TEMPLATE_ITERATION_RANDOM_FILE = new File(TEST_DIR, "user-template-iteration-random.xml"); - protected static final String USER_TEMPLATE_ITERATION_RANDOM_OID = "10000000-0000-0000-0000-0000000d0002"; // SAME OID as USER_TEMPLATE_ITERATION // Iteration with token expression (sequential) and post-condition that checks for e-mail uniquness. protected static final File USER_TEMPLATE_ITERATION_UNIQUE_EMAIL_FILE = new File(TEST_DIR, "user-template-iteration-unique-email.xml"); @@ -140,7 +106,6 @@ public class TestIteration extends AbstractInitializedModelIntegrationTest { private static final String ACCOUNT_DEWATT_NAME = "DeWatt"; private static final String USER_LARGO_NAME = "largo"; - private static final String ACCOUNT_LARGO_NAME = "largo"; public static final String ACCOUNT_LARGO_DUMMY_USERNAME = "largo"; private static final String DESCRIPTION_RUM = "Where's the rum?"; @@ -226,8 +191,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100JackAssignAccountDummyConflicting() throws Exception { - final String TEST_NAME = "test100JackAssignAccountDummyConflicting"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -280,8 +243,6 @@ public void test100JackAssignAccountDummyConflicting() throws Exception { @Test public void test200JackAssignAccountDummyPinkConflicting() throws Exception { - final String TEST_NAME = "test200JackAssignAccountDummyPinkConflicting"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -296,7 +257,7 @@ public void test200JackAssignAccountDummyPinkConflicting() throws Exception { repoAddObject(createShadow(getDummyResourceObject(RESOURCE_DUMMY_PINK_NAME), ACCOUNT_JACK_DUMMY_USERNAME), result); // assignment with weapon := 'pistol' (test for - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); AssignmentType assignmentType = createConstructionAssignment(RESOURCE_DUMMY_PINK_OID, ShadowKindType.ACCOUNT, null); ConstructionType constructionType = assignmentType.getConstruction(); ResourceAttributeDefinitionType attributeDefinitionType = new ResourceAttributeDefinitionType(); @@ -363,8 +324,6 @@ public void test200JackAssignAccountDummyPinkConflicting() throws Exception { */ @Test public void test210GuybrushAssignAccountDummyPink() throws Exception { - final String TEST_NAME = "test210GuybrushAssignAccountDummyPink"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -415,8 +374,6 @@ public void test210GuybrushAssignAccountDummyPink() throws Exception { @Test public void test220DeWattAssignAccountDummyPinkCaseIgnore() throws Exception { - final String TEST_NAME = "test220DeWattAssignAccountDummyPinkCaseIgnore"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -427,7 +384,7 @@ public void test220DeWattAssignAccountDummyPinkCaseIgnore() throws Exception { PrismObject accountDeWatt = createAccount(getDummyResourceObject(RESOURCE_DUMMY_PINK_NAME), ACCOUNT_DEWATT_NAME, true); addAttributeToShadow(accountDeWatt, getDummyResourceObject(RESOURCE_DUMMY_PINK_NAME), - DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Augustus DeWatt"); + DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Augustus DeWatt"); addObject(accountDeWatt); // precondition @@ -457,7 +414,7 @@ public void test220DeWattAssignAccountDummyPinkCaseIgnore() throws Exception { // Check shadow PrismObject accountPinkShadow = repositoryService.getObject(ShadowType.class, accountPinkOid, null, result); - assertAccountShadowRepo(accountPinkShadow, accountPinkOid, USER_DEWATT_NAME+"1", getDummyResourceType(RESOURCE_DUMMY_PINK_NAME)); + assertAccountShadowRepo(accountPinkShadow, accountPinkOid, USER_DEWATT_NAME + "1", getDummyResourceType(RESOURCE_DUMMY_PINK_NAME)); // Check account PrismObject accountPinkModel = modelService.getObject(ShadowType.class, accountPinkOid, null, task, result); @@ -466,7 +423,7 @@ public void test220DeWattAssignAccountDummyPinkCaseIgnore() throws Exception { // Old account assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_DEWATT_NAME, "Augustus DeWatt", true); // The new account - assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, USER_DEWATT_NAME+"1", "Augustus DeWatt", true); + assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, USER_DEWATT_NAME + "1", "Augustus DeWatt", true); // Check audit display("Audit", dummyAuditService); @@ -481,8 +438,6 @@ public void test220DeWattAssignAccountDummyPinkCaseIgnore() throws Exception { @Test public void test230ScroogeAddAccountDummyConflictingNoShadow() throws Exception { - final String TEST_NAME = "test230ScroogeAddAccountDummyConflictingNoShadow"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -528,12 +483,9 @@ public void test230ScroogeAddAccountDummyConflictingNoShadow() throws Exception /** * This tests a situation where the ObjectAlreadyExists conflict occurs because of some misconfiguration. * For example, the reason of the conflict is not the naming attribute itself. - * @throws Exception */ @Test public void test235HackerAddAccountDummyEternalConflict() throws Exception { - final String TEST_NAME = "test235HackerAddAccountDummyEternalConflict"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -577,8 +529,6 @@ public void test235HackerAddAccountDummyEternalConflict() throws Exception { @Test public void test240LargoAssignAccountDummyConflictingNoShadow() throws Exception { - final String TEST_NAME = "test240LargoAssignAccountDummyConflictingNoShadow"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -590,8 +540,8 @@ public void test240LargoAssignAccountDummyConflictingNoShadow() throws Exception account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Largo Pinky"); getDummyResource(RESOURCE_DUMMY_PINK_NAME).addAccount(account); - Collection> deltas = new ArrayList<>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_LARGO_OID, RESOURCE_DUMMY_PINK_OID, null, true); + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta( + USER_LARGO_OID, RESOURCE_DUMMY_PINK_OID, null, true); // WHEN when(); @@ -633,19 +583,17 @@ public void test240LargoAssignAccountDummyConflictingNoShadow() throws Exception * Doing the same as test240 (conflict without pre-existing shadow -> surprising the model with AlreadyExists, * causing re-running given wave in model. But this time doing this on resource that has synchronization * defined (fuchsia). - * + *

* test260: first case - existing account corresponds to user being created - * + *

* 1) manually create account Jupiter Jones (no shadow!), description = "jupiter" * 2) create user Jupiter Jones (name = jupiter) - * + *

* Create account operation should fail, account should be synchronized back to repo (creating the user!), and * model should clean it up somehow... */ @Test public void test260JupiterConflictNoShadowSyncBack() throws Exception { - final String TEST_NAME = "test260JupiterConflictNoShadowSyncBack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -657,7 +605,6 @@ public void test260JupiterConflictNoShadowSyncBack() throws Exception { account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, USER_JUPITER_NAME); // jupiter getDummyResource(RESOURCE_DUMMY_FUCHSIA_NAME).addAccount(account); - Collection> deltas = new ArrayList<>(); PrismObject userJupiter = PrismTestUtil.parseObject(USER_JUPITER_FILE); // WHEN @@ -688,23 +635,19 @@ public void test260JupiterConflictNoShadowSyncBack() throws Exception { // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } // remove the assignment, shadow and account to prepare for following tests @Test public void test262JupiterCleanup() throws Exception { - final String TEST_NAME = "test262JupiterCleanup"; - cleanUpJupiter(TEST_NAME); + cleanUpJupiter(); } - protected void cleanUpJupiter(String TEST_NAME) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException, SchemaViolationException, ConflictException, InterruptedException { + protected void cleanUpJupiter() + throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException, SchemaViolationException, + ConflictException, InterruptedException { // GIVEN Task task = getTestTask(); @@ -730,13 +673,6 @@ protected void cleanUpJupiter(String TEST_NAME) throws SchemaException, ObjectAl // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } /** @@ -744,8 +680,6 @@ protected void cleanUpJupiter(String TEST_NAME) throws SchemaException, ObjectAl */ @Test public void test264JupiterConflictNoShadowSyncBackSeparate() throws Exception { - final String TEST_NAME = "test264JupiterConflictNoShadowSyncBackSeparate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -787,20 +721,12 @@ public void test264JupiterConflictNoShadowSyncBackSeparate() throws Exception { // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } // remove the assignment, shadow and account to prepare for following tests @Test public void test266JupiterCleanupAgain() throws Exception { - final String TEST_NAME = "test266JupiterCleanupAgain"; - cleanUpJupiter(TEST_NAME); + cleanUpJupiter(); } /** @@ -809,8 +735,6 @@ public void test266JupiterCleanupAgain() throws Exception { */ @Test public void test270JupiterConflictOtherNoShadowSyncBack() throws Exception { - final String TEST_NAME = "test270JupiterConflictOtherNoShadowSyncBack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -872,13 +796,6 @@ public void test270JupiterConflictOtherNoShadowSyncBack() throws Exception { // TODO Check audit display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(3); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(2); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertExecutionSuccess(); } private void assertUserJupiter(PrismObject user) { @@ -890,8 +807,6 @@ private void assertUserJupiter(PrismObject user) { */ @Test public void test280RenameBobNoShadow() throws Exception { - final String TEST_NAME = "test280RenameBobNoShadow"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -950,8 +865,6 @@ public void test280RenameBobNoShadow() throws Exception { */ @Test public void test282RenamePeterNoShadowSync() throws Exception { - final String TEST_NAME = "test282RenamePeterNoShadowSync"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1026,8 +939,6 @@ public void test282RenamePeterNoShadowSync() throws Exception { // as with jupiter, but ADD instead of ASSIGN account @Test public void test290AlfredConflictNoShadowSyncBackAdd() throws Exception { - final String TEST_NAME = "test290AlfredConflictNoShadowSyncBackAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1039,7 +950,6 @@ public void test290AlfredConflictNoShadowSyncBackAdd() throws Exception { account.addAttributeValues(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_AD_SAM_ACCOUNT_NAME_NAME, "alfred"); getDummyResource(RESOURCE_DUMMY_FUCHSIA_NAME).addAccount(account); - Collection> deltas = new ArrayList<>(); PrismObject userAlfred = PrismTestUtil.parseObject(USER_ALFRED_FILE); PrismObject accountAlfred = PrismTestUtil.parseObject(ACCOUNT_ALFRED_FILE); ObjectReferenceType linkRef = new ObjectReferenceType(); @@ -1073,12 +983,8 @@ public void test290AlfredConflictNoShadowSyncBackAdd() throws Exception { assertDummyAccount(RESOURCE_DUMMY_FUCHSIA_NAME, "Alfred Hitchcock", null, true); } - - @Test public void test300JackAssignAccountDummyVioletConflicting() throws Exception { - final String TEST_NAME = "test300JackAssignAccountDummyVioletConflicting"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1143,8 +1049,6 @@ public void test300JackAssignAccountDummyVioletConflicting() throws Exception { @Test public void test350GuybrushAssignAccountDummyViolet() throws Exception { - final String TEST_NAME = "test350GuybrushAssignAccountDummyViolet"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1199,8 +1103,6 @@ public void test350GuybrushAssignAccountDummyViolet() throws Exception { @Test public void test360HermanAssignAccountDummyViolet() throws Exception { - final String TEST_NAME = "test360HermanAssignAccountDummyViolet"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1258,8 +1160,6 @@ public void test360HermanAssignAccountDummyViolet() throws Exception { @Test public void test400RenameAngelicaConflicting() throws Exception { - final String TEST_NAME = "test400RenameAngelicaConflicting"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1282,7 +1182,7 @@ public void test400RenameAngelicaConflicting() throws Exception { // THEN assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME, null, true); - assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME+"1", "Angelica", true); + assertDummyAccount(RESOURCE_DUMMY_PINK_NAME, ACCOUNT_SPARROW_NAME + "1", "Angelica", true); assertNoDummyAccount(RESOURCE_DUMMY_PINK_NAME, USER_ANGELICA_NAME); } @@ -1291,8 +1191,6 @@ public void test400RenameAngelicaConflicting() throws Exception { */ @Test public void test500JackAssignAccountDummyMagenta() throws Exception { - final String TEST_NAME = "test500JackAssignAccountDummyMagenta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1359,8 +1257,6 @@ public void test500JackAssignAccountDummyMagenta() throws Exception { */ @Test public void test510DrakeAssignAccountDummyMagenta() throws Exception { - final String TEST_NAME = "test510DrakeAssignAccountDummyMagenta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1438,8 +1334,6 @@ public void test510DrakeAssignAccountDummyMagenta() throws Exception { */ @Test public void test520DrakeModifyLocality() throws Exception { - final String TEST_NAME = "test520DrakeModifyLocality"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1502,8 +1396,6 @@ public void test520DrakeModifyLocality() throws Exception { */ @Test public void test530GuybrushAssignAccountDummyMagenta() throws Exception { - final String TEST_NAME = "test530GuybrushAssignAccountDummyMagenta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1568,8 +1460,6 @@ public void test530GuybrushAssignAccountDummyMagenta() throws Exception { */ @Test public void test532GuybrushModifyDescription() throws Exception { - final String TEST_NAME = "test532GuybrushModifyDescription"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1610,9 +1500,9 @@ public void test532GuybrushModifyDescription() throws Exception { // There should be no account with the "straight" name assertNoDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); // Renamed - assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME+ "001", "Guybrush Threepwood", true); + assertDummyAccount(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME + "001", "Guybrush Threepwood", true); - assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME+ "001", + assertDummyAccountAttribute(RESOURCE_DUMMY_MAGENTA_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME + "001", DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, DESCRIPTION_RUM + " -- Guybrush Threepwood"); PrismAsserts.assertPropertyValue(userGuybrush, UserType.F_ORGANIZATION, @@ -1631,8 +1521,6 @@ public void test532GuybrushModifyDescription() throws Exception { @Test public void test600JackRename() throws Exception { - final String TEST_NAME = "test600JackRename"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1692,8 +1580,6 @@ public void test600JackRename() throws Exception { @Test public void test700DarkVioletSyncTask() throws Exception { - final String TEST_NAME = "test700DarkVioletSyncTask"; - // WHEN importObjectFromFile(TASK_LIVE_SYNC_DUMMY_DARK_VIOLET_FILE); @@ -1706,8 +1592,6 @@ public void test700DarkVioletSyncTask() throws Exception { */ @Test public void test710DarkVioletAddLeChuck() throws Exception { - final String TEST_NAME = "test710DarkVioletAddLeChuck"; - // GIVEN dummyAuditService.clear(); @@ -1733,8 +1617,6 @@ public void test710DarkVioletAddLeChuck() throws Exception { */ @Test public void test712DarkVioletAddCharles() throws Exception { - final String TEST_NAME = "test712DarkVioletAddCharles"; - // GIVEN dummyAuditService.clear(); @@ -1753,7 +1635,7 @@ public void test712DarkVioletAddCharles() throws Exception { // THEN then(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); + assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".1"); } /* @@ -1761,8 +1643,6 @@ public void test712DarkVioletAddCharles() throws Exception { */ @Test public void test714DarkVioletAddShinetop() throws Exception { - final String TEST_NAME = "test714DarkVioletAddShinetop"; - // GIVEN dummyAuditService.clear(); @@ -1782,14 +1662,12 @@ public void test714DarkVioletAddShinetop() throws Exception { // THEN then(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); - assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2", "Melee Island"); + assertUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".1"); + assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".2", "Melee Island"); } @Test public void test716DarkVioletDeleteCharles() throws Exception { - final String TEST_NAME = "test716DarkVioletDeleteCharles"; - // GIVEN dummyAuditService.clear(); @@ -1803,14 +1681,12 @@ public void test716DarkVioletDeleteCharles() throws Exception { // THEN then(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); - assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2", "Melee Island"); + assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME + ".1"); + assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".2", "Melee Island"); } @Test public void test720DarkVioletModifyShinetopLocation() throws Exception { - final String TEST_NAME = "test720DarkVioletModifyShinetopLocation"; - // GIVEN dummyAuditService.clear(); @@ -1827,14 +1703,12 @@ public void test720DarkVioletModifyShinetopLocation() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); - assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2", "Monkey Island"); + assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME + ".1"); + assertUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME + ".2", "Monkey Island"); } @Test public void test722DarkVioletModifyShinetopFullName() throws Exception { - final String TEST_NAME = "test722DarkVioletModifyShinetopFullName"; - // GIVEN dummyAuditService.clear(); @@ -1851,9 +1725,9 @@ public void test722DarkVioletModifyShinetopFullName() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".1"); + assertNoUserNick(ACCOUNT_CHARLES_USERNAME, LECHUCK_FULLNAME + ".1"); assertUserNick(ACCOUNT_SHINETOP_USERNAME, CHUCKIE_FULLNAME, CHUCKIE_FULLNAME, "Monkey Island"); - assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2"); + assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME + ".2"); } /* @@ -1865,8 +1739,6 @@ public void test722DarkVioletModifyShinetopFullName() throws Exception { */ @Test public void test724DarkVioletAddLe_Chuck() throws Exception { - final String TEST_NAME = "test724DarkVioletAddLe_Chuck"; - // GIVEN dummyAuditService.clear(); @@ -1887,9 +1759,9 @@ public void test724DarkVioletAddLe_Chuck() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_LECHUCK_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME); - assertUserNick(ACCOUNT_LE_CHUCK_USERNAME, LE_CHUCK_FULLNAME, LE_CHUCK_FULLNAME+".1", "Melee Island"); + assertUserNick(ACCOUNT_LE_CHUCK_USERNAME, LE_CHUCK_FULLNAME, LE_CHUCK_FULLNAME + ".1", "Melee Island"); assertUserNick(ACCOUNT_SHINETOP_USERNAME, CHUCKIE_FULLNAME, CHUCKIE_FULLNAME, "Monkey Island"); - assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME, LECHUCK_FULLNAME+".2"); + assertNoUserNick(ACCOUNT_SHINETOP_USERNAME, LECHUCK_FULLNAME + ".2"); } /* @@ -1898,11 +1770,7 @@ public void test724DarkVioletAddLe_Chuck() throws Exception { */ @Test public void test730DarkVioletAddBarbossa() throws Exception { - final String TEST_NAME = "test730DarkVioletAddBarbossa"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount(USER_BARBOSSA_USERNAME); @@ -1919,7 +1787,7 @@ public void test730DarkVioletAddBarbossa() throws Exception { // THEN then(); - assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME+".1"); + assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME + ".1"); } /* @@ -1930,11 +1798,7 @@ public void test730DarkVioletAddBarbossa() throws Exception { */ @Test public void test732DarkVioletAddBarbossa() throws Exception { - final String TEST_NAME = "test732DarkVioletAddBarbossa"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount("YA" + USER_BARBOSSA_USERNAME); @@ -1951,14 +1815,12 @@ public void test732DarkVioletAddBarbossa() throws Exception { // THEN then(); - assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME+".1"); - assertUserNick("YA" + USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME+".4"); + assertUserNick(USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME + ".1"); + assertUserNick("YA" + USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME, USER_BARBOSSA_USERNAME + ".4"); } @Test public void test750DarkVioletAddMatusalem() throws Exception { - final String TEST_NAME = "test750DarkVioletAddMatusalem"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1990,11 +1852,7 @@ public void test750DarkVioletAddMatusalem() throws Exception { */ @Test public void test752DarkVioletAddDiplomatico() throws Exception { - final String TEST_NAME = "test752DarkVioletAddDiplomatico"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount(ACCOUNT_DIPLOMATICO_USERNAME); @@ -2016,7 +1874,7 @@ public void test752DarkVioletAddDiplomatico() throws Exception { assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); iterationTokenDiplomatico = lookupIterationTokenByAdditionalName(ACCOUNT_DIPLOMATICO_USERNAME); - assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenDiplomatico); } /* @@ -2024,11 +1882,7 @@ public void test752DarkVioletAddDiplomatico() throws Exception { */ @Test public void test754DarkVioletAddMilionario() throws Exception { - final String TEST_NAME = "test754DarkVioletAddMilionario"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = new DummyAccount(ACCOUNT_MILLONARIO_USERNAME); @@ -2047,19 +1901,15 @@ public void test754DarkVioletAddMilionario() throws Exception { // THEN then(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenDiplomatico); iterationTokenMillonario = lookupIterationTokenByAdditionalName(ACCOUNT_MILLONARIO_USERNAME); - assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Peru"); + assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenMillonario, "Peru"); } @Test public void test756DarkVioletDeleteDiplomatico() throws Exception { - final String TEST_NAME = "test756DarkVioletDeleteDiplomatico"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); // WHEN @@ -2072,17 +1922,13 @@ public void test756DarkVioletDeleteDiplomatico() throws Exception { // THEN then(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); - assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Peru"); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); + assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenMillonario, "Peru"); } @Test public void test760DarkVioletModifyMillonarioLocation() throws Exception { - final String TEST_NAME = "test760DarkVioletModifyMillonarioLocation"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = getDummyResource(RESOURCE_DUMMY_DARK_VIOLET_NAME).getAccountByUsername(ACCOUNT_MILLONARIO_USERNAME); @@ -2098,8 +1944,8 @@ public void test760DarkVioletModifyMillonarioLocation() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); - assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario, "Northern Peru"); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); + assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME + iterationTokenMillonario, "Northern Peru"); } /** @@ -2107,11 +1953,7 @@ public void test760DarkVioletModifyMillonarioLocation() throws Exception { */ @Test public void test762DarkVioletModifyMillonarioFullName() throws Exception { - final String TEST_NAME = "test762DarkVioletModifyMillonarioFullName"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = getDummyResource(RESOURCE_DUMMY_DARK_VIOLET_NAME).getAccountByUsername(ACCOUNT_MILLONARIO_USERNAME); @@ -2127,9 +1969,9 @@ public void test762DarkVioletModifyMillonarioFullName() throws Exception { then(); displayAllUsers(); assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RON_FULLNAME, RON_FULLNAME, "Northern Peru"); - assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario); + assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME + iterationTokenMillonario); } /** @@ -2137,11 +1979,7 @@ public void test762DarkVioletModifyMillonarioFullName() throws Exception { */ @Test public void test764DarkVioletModifyMatusalemFullName() throws Exception { - final String TEST_NAME = "test764DarkVioletModifyMatusalemFullName"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); dummyAuditService.clear(); DummyAccount account = getDummyResource(RESOURCE_DUMMY_DARK_VIOLET_NAME).getAccountByUsername(ACCOUNT_MATUSALEM_USERNAME); @@ -2156,22 +1994,19 @@ public void test764DarkVioletModifyMatusalemFullName() throws Exception { // THEN then(); displayAllUsers(); - assertNoUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME, RUM_FULLNAME); + assertNoUserNick(ACCOUNT_MATUSALEM_USERNAME, RUM_FULLNAME); String iterationTokenMatusalem = lookupIterationTokenByAdditionalName(ACCOUNT_MATUSALEM_USERNAME); - assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RON_FULLNAME, RON_FULLNAME+iterationTokenMatusalem); - assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenDiplomatico); + assertUserNick(ACCOUNT_MATUSALEM_USERNAME, RON_FULLNAME, RON_FULLNAME + iterationTokenMatusalem); + assertNoUserNick(ACCOUNT_DIPLOMATICO_USERNAME, RUM_FULLNAME + iterationTokenDiplomatico); assertUserNick(ACCOUNT_MILLONARIO_USERNAME, RON_FULLNAME, RON_FULLNAME, "Northern Peru"); - assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME, RUM_FULLNAME+iterationTokenMillonario); + assertNoUserNick(ACCOUNT_MILLONARIO_USERNAME, RUM_FULLNAME + iterationTokenMillonario); } - /** * MID-2887 */ @Test - public void test800UniqeEmailAddUserAlfredoFettucini() throws Exception { - final String TEST_NAME = "test800UniqeEmailAddUserAlfredoFettucini"; - + public void test800UniqueEmailAddUserAlfredoFettucini() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2179,8 +2014,9 @@ public void test800UniqeEmailAddUserAlfredoFettucini() throws Exception { setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_ITERATION_UNIQUE_EMAIL_OID); - PrismObject user = createUser(USER_ALFREDO_FETTUCINI_USERNAME, USER_ALFREDO_FETTUCINI_GIVEN_NAME, USER_ALFREDO_FETTUCINI_FAMILY_NAME, - USER_FETTUCINI_NICKNAME, true); + PrismObject user = createUser( + USER_ALFREDO_FETTUCINI_USERNAME, USER_ALFREDO_FETTUCINI_GIVEN_NAME, + USER_ALFREDO_FETTUCINI_FAMILY_NAME, USER_FETTUCINI_NICKNAME, true); // WHEN when(); @@ -2197,18 +2033,16 @@ public void test800UniqeEmailAddUserAlfredoFettucini() throws Exception { USER_ALFREDO_FETTUCINI_GIVEN_NAME + " " + USER_ALFREDO_FETTUCINI_FAMILY_NAME, USER_ALFREDO_FETTUCINI_GIVEN_NAME, USER_ALFREDO_FETTUCINI_FAMILY_NAME); - PrismAsserts.assertEqualsPolyString("Wrong "+user+" nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); + PrismAsserts.assertEqualsPolyString("Wrong " + user + " nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); - assertEquals("Wrong "+user+" emailAddress", USER_FETTUCINI_NICKNAME + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); + assertEquals("Wrong " + user + " emailAddress", USER_FETTUCINI_NICKNAME + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); } /** * MID-2887 */ @Test - public void test802UniqeEmailAddUserBillFettucini() throws Exception { - final String TEST_NAME = "test802UniqeEmailAddUserBillFettucini"; - + public void test802UniqueEmailAddUserBillFettucini() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2233,9 +2067,9 @@ public void test802UniqeEmailAddUserBillFettucini() throws Exception { USER_BILL_FETTUCINI_GIVEN_NAME + " " + USER_BILL_FETTUCINI_FAMILY_NAME, USER_BILL_FETTUCINI_GIVEN_NAME, USER_BILL_FETTUCINI_FAMILY_NAME); - PrismAsserts.assertEqualsPolyString("Wrong "+user+" nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); + PrismAsserts.assertEqualsPolyString("Wrong " + user + " nickname", USER_FETTUCINI_NICKNAME, userAfter.asObjectable().getNickName()); - assertEquals("Wrong "+user+" emailAddress", USER_FETTUCINI_NICKNAME + ".1" + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); + assertEquals("Wrong " + user + " emailAddress", USER_FETTUCINI_NICKNAME + ".1" + EMAIL_SUFFIX, userAfter.asObjectable().getEmailAddress()); } /** @@ -2243,8 +2077,6 @@ public void test802UniqeEmailAddUserBillFettucini() throws Exception { */ @Test public void test820SubtypeSetByInbound() throws Exception { - final String TEST_NAME = "test820SubtypeSetByInbound"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2304,22 +2136,24 @@ private void assertUserNick(String accountName, String accountFullName, String e private void assertUserNick(String accountName, String accountFullName, String expectedUserName, String expectedLocality) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(expectedUserName); - assertNotNull("No user for "+accountName+" ("+expectedUserName+")", user); - display("Created user for "+accountName, user); - assertEquals("Wrong nickname in user created for "+accountName, accountFullName, user.asObjectable().getNickName().getOrig()); - assertEquals("Wrong additionalName in user created for "+accountName, accountName, user.asObjectable().getAdditionalName().getOrig()); + assertNotNull("No user for " + accountName + " (" + expectedUserName + ")", user); + display("Created user for " + accountName, user); + assertEquals("Wrong nickname in user created for " + accountName, accountFullName, user.asObjectable().getNickName().getOrig()); + assertEquals("Wrong additionalName in user created for " + accountName, accountName, user.asObjectable().getAdditionalName().getOrig()); PolyStringType locality = user.asObjectable().getLocality(); if (locality == null) { - assertEquals("Wrong locality in user created for "+accountName, expectedLocality, null); + assertNull("Wrong locality in user created for " + accountName, expectedLocality); } else { - assertEquals("Wrong locality in user created for "+accountName, expectedLocality, locality.getOrig()); + assertEquals("Wrong locality in user created for " + accountName, expectedLocality, locality.getOrig()); } } - private void assertNoUserNick(String accountName, String accountFullName, String expectedUserName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private void assertNoUserNick(String accountName, String expectedUserName) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(expectedUserName); - display("User for "+accountName, user); - assertNull("User for "+accountName+" ("+expectedUserName+") exists but it should be gone", user); + display("User for " + accountName, user); + assertNull("User for " + accountName + " (" + expectedUserName + ") exists but it should be gone", user); } private String lookupIterationTokenByAdditionalName(String additionalName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -2332,7 +2166,7 @@ private String lookupIterationTokenByAdditionalName(String additionalName) throw if (objects.isEmpty()) { return null; } - assert objects.size() == 1 : "Too many objects found for additional name "+additionalName+": "+objects; + assert objects.size() == 1 : "Too many objects found for additional name " + additionalName + ": " + objects; PrismObject user = objects.iterator().next(); return user.asObjectable().getIterationToken(); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java index b08bf160ffe..d83bb2953da 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestLifecycle.java @@ -25,11 +25,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author Radovan Semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestLifecycle extends AbstractInitializedModelIntegrationTest { @@ -51,16 +47,12 @@ public class TestLifecycle extends AbstractInitializedModelIntegrationTest { //no subtype, forced in draft state public static final File ROLE_CROUPIER_FILE = new File(TEST_DIR, "role-croupier.xml"); - protected static final String ROLE_CROUPIER_OID = "a7b8de9a-20a1-84f6-b452-01254a1256e3"; public static final File ROLE_PIT_BOSS_FILE = new File(TEST_DIR, "role-pit-boss.xml"); - protected static final String ROLE_PIT_BOSS_OID = "c4525ef8-31d4-95e6-d542-745e263f596c"; public static final String SUBTYPE_EMPLOYEE = "employee"; private static final Object USER_JACK_TELEPHONE_NUMBER = "12345654321"; - private String accontJackOid; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -87,8 +79,6 @@ protected File getSystemConfigurationFile() { */ @Test public void test050SetupJack() throws Exception { - final String TEST_NAME = "test050SetupJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -118,9 +108,6 @@ public void test050SetupJack() throws Exception { @Test public void test052PrincipalJackDraft() throws Exception { - final String TEST_NAME = "test052AutzJackDraft"; - // GIVEN - // WHEN when(); MidPointPrincipal principal = focusProfileService.getPrincipal(USER_JACK_USERNAME, UserType.class); @@ -140,8 +127,6 @@ public void test052PrincipalJackDraft() throws Exception { */ @Test public void test060TransitionJackToProposed() throws Exception { - final String TEST_NAME = "test060TransitionJackToProposed"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -162,14 +147,11 @@ public void test060TransitionJackToProposed() throws Exception { // Although we are in the proposed lifecycle and assignments would not be active by default // the proposed lifecycle is forcing activation to enabled. Therefore also assignments are // considered active. - accontJackOid = getSingleLinkOid(userAfter); + getSingleLinkOid(userAfter); } @Test public void test062PrincipalJackProposed() throws Exception { - final String TEST_NAME = "test062PrincipalJackProposed"; - // GIVEN - // WHEN when(); MidPointPrincipal principal = focusProfileService.getPrincipal(USER_JACK_USERNAME, UserType.class); @@ -194,8 +176,6 @@ public void test062PrincipalJackProposed() throws Exception { */ @Test public void test090TransitionJackToDefaultActive() throws Exception { - final String TEST_NAME = "test090TransitionJackToDefaultActive"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -219,9 +199,6 @@ public void test090TransitionJackToDefaultActive() throws Exception { @Test public void test092PrincipalJackDefaultActive() throws Exception { - final String TEST_NAME = "test092PrincipalJackDefaultActive"; - // GIVEN - // WHEN when(); MidPointPrincipal principal = focusProfileService.getPrincipal(USER_JACK_USERNAME, UserType.class); @@ -231,23 +208,21 @@ public void test092PrincipalJackDefaultActive() throws Exception { assertNotAuthorized(principal, AUTZ_COMMAND_URL); assertAuthorized(principal, AUTZ_GAMBLE_URL); assertAuthorized(principal, AUTZ_APPARATE_URL); - // Forced assignment not specified for active lifecycle state + // Forced assignment not specified for active lifecycle state assertNotAuthorized(principal, AUTZ_PIT_BOSS_URL); assertNotAuthorized(principal, AUTZ_CROUPIER_URL); } private void assertTelephoneNumber(PrismObject user, Object expectedTelephoneNumber) { - assertEquals("Wrong telephoe number in "+user, expectedTelephoneNumber, user.asObjectable().getTelephoneNumber()); + assertEquals("Wrong telephoe number in " + user, expectedTelephoneNumber, user.asObjectable().getTelephoneNumber()); } protected void assertLifecycleState(PrismObject object, String expectedLifecycleState) { - assertEquals("Wrong lifecycle state in "+object, expectedLifecycleState, object.asObjectable().getLifecycleState()); + assertEquals("Wrong lifecycle state in " + object, expectedLifecycleState, object.asObjectable().getLifecycleState()); } @Test public void test100AssignJackCaretaker() throws Exception { - final String TEST_NAME = "test100AssignJackCaretaker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -270,8 +245,6 @@ public void test100AssignJackCaretaker() throws Exception { @Test public void test102UnassignJackHeadmaster() throws Exception { - final String TEST_NAME = "test102UnassignJackHeadmaster"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -298,8 +271,6 @@ public void test102UnassignJackHeadmaster() throws Exception { */ @Test public void test110UnassignJackCaretaker() throws Exception { - final String TEST_NAME = "test110UnassignJackCaretaker"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -325,8 +296,6 @@ public void test110UnassignJackCaretaker() throws Exception { */ @Test public void test112UnassignJackCaretaker() throws Exception { - final String TEST_NAME = "test110UnassignJackCaretaker"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java index 233651495f0..269485b6e2c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestMerge.java @@ -26,10 +26,6 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author semancik - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMerge extends AbstractInitializedModelIntegrationTest { @@ -69,8 +65,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - PrismObject userJackBefore = getUser(USER_JACK_OID); display("Jack before", userJackBefore); @@ -96,9 +90,7 @@ public void test000Sanity() throws Exception { */ @Test public void test100MergeJackGuybrushPreviewDelta() throws Exception { - final String TEST_NAME = "test100MergeJackGuybrushPreviewDelta"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJackBefore = getUser(USER_JACK_OID); @@ -158,9 +150,7 @@ public void test100MergeJackGuybrushPreviewDelta() throws Exception { */ @Test public void test102MergeJackGuybrushPreviewObject() throws Exception { - final String TEST_NAME = "test102MergeJackGuybrushPreviewObject"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -208,9 +198,7 @@ public void test102MergeJackGuybrushPreviewObject() throws Exception { */ @Test public void test110MergeGuybrushJackPreviewDelta() throws Exception { - final String TEST_NAME = "test110MergeGuybrushJackPreviewDelta"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userGuybrushBefore = getUser(USER_GUYBRUSH_OID); @@ -267,9 +255,7 @@ public void test110MergeGuybrushJackPreviewDelta() throws Exception { */ @Test public void test112MergeGuybrushJackPreviewObject() throws Exception { - final String TEST_NAME = "test112MergeGuybrushJackPreviewObject"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -314,9 +300,7 @@ public void test112MergeGuybrushJackPreviewObject() throws Exception { */ @Test public void test200MergeJackGuybrushExpressionPreviewDelta() throws Exception { - final String TEST_NAME = "test200MergeJackGuybrushExpressionPreviewDelta"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJackBefore = getUser(USER_JACK_OID); @@ -366,9 +350,7 @@ public void test200MergeJackGuybrushExpressionPreviewDelta() throws Exception { */ @Test public void test202MergeJackGuybrushExpressionPreviewObject() throws Exception { - final String TEST_NAME = "test202MergeJackGuybrushExpressionPreviewObject"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -416,9 +398,7 @@ public void test202MergeJackGuybrushExpressionPreviewObject() throws Exception { */ @Test public void test300MergeJackGuybrushPreviewDeltaDefaultSpecific() throws Exception { - final String TEST_NAME = "test300MergeJackGuybrushPreviewDeltaDefaultSpecific"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJackBefore = getUser(USER_JACK_OID); @@ -478,9 +458,7 @@ public void test300MergeJackGuybrushPreviewDeltaDefaultSpecific() throws Excepti */ @Test public void test500MergeJackGuybrush() throws Exception { - final String TEST_NAME = "test500MergeJackGuybrush"; - - Task task = taskManager.createTaskInstance(TestMerge.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java index 42d5fbf3cb2..cf628993b63 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelCrudService.java @@ -6,12 +6,12 @@ */ package com.evolveum.midpoint.model.intest; +import static org.testng.AssertJUnit.*; + import java.io.File; import java.util.ArrayList; import java.util.Collection; -import com.evolveum.midpoint.test.IntegrationTestTools; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; @@ -28,18 +28,17 @@ import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; - -import static org.testng.AssertJUnit.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * This is testing the DEPRECATED functions of model API. It should be removed once the functions are phased out. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestModelCrudService extends AbstractInitializedModelIntegrationTest { @@ -54,15 +53,13 @@ public class TestModelCrudService extends AbstractInitializedModelIntegrationTes private static String accountOid; - @Autowired(required = true) + @Autowired protected ModelCrudService modelCrudService; @Test public void test050AddResource() throws Exception { - final String TEST_NAME = "test050AddResource"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); @@ -85,16 +82,14 @@ public void test050AddResource() throws Exception { @Test public void test100ModifyUserAddAccount() throws Exception { - final String TEST_NAME = "test100ModifyUserAddAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelCrudService.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference() @@ -102,7 +97,7 @@ public void test100ModifyUserAddAccount() throws Exception { modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN // Check accountRef @@ -140,14 +135,14 @@ public void test119ModifyUserDeleteAccount() throws Exception { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); account.setOid(accountOid); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN // Check accountRef @@ -158,8 +153,8 @@ public void test119ModifyUserDeleteAccount() throws Exception { // Check is shadow is gone try { - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - AssertJUnit.fail("Shadow "+accountOid+" still exists"); + repositoryService.getObject(ShadowType.class, accountOid, null, result); + AssertJUnit.fail("Shadow " + accountOid + " still exists"); } catch (ObjectNotFoundException e) { // This is OK } @@ -208,12 +203,12 @@ public void test121ModifyUserAddAccountRef() throws Exception { OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountOid); modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN // Check accountRef @@ -233,8 +228,6 @@ public void test121ModifyUserAddAccountRef() throws Exception { assertDefaultDummyAccount("jack", "Jack Sparrow", true); } - - @Test public void test128ModifyUserDeleteAccountRef() throws Exception { @@ -245,14 +238,14 @@ public void test128ModifyUserDeleteAccountRef() throws Exception { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), accountOid); modifications.add(accountDelta); // WHEN - modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications , null, task, result); + modelCrudService.modifyObject(UserType.class, USER_JACK_OID, modifications, null, task, result); // THEN PrismObject userJack = getUser(USER_JACK_OID); @@ -308,7 +301,7 @@ public void test150AddUserBlackbeardWithAccount() throws Exception { addAccountLinkRef(user, new File(TEST_CONTRACT_DIR, "account-blackbeard-dummy.xml")); // WHEN - modelCrudService.addObject(user , null, task, result); + modelCrudService.addObject(user, null, task, result); // THEN // Check accountRef @@ -331,7 +324,6 @@ public void test150AddUserBlackbeardWithAccount() throws Exception { assertDefaultDummyAccount("blackbeard", "Edward Teach", true); } - @Test public void test210AddUserMorganWithAssignment() throws Exception { @@ -343,7 +335,7 @@ public void test210AddUserMorganWithAssignment() throws Exception { PrismObject user = PrismTestUtil.parseObject(new File(TEST_CONTRACT_DIR, "user-morgan-assignment-dummy.xml")); // WHEN - modelCrudService.addObject(user , null, task, result); + modelCrudService.addObject(user, null, task, result); // THEN // Check accountRef diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java index 65a6d18359a..2e624b724f1 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestModelServiceContract.java @@ -6,36 +6,17 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; - import javax.xml.bind.JAXBElement; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.icf.dummy.resource.BreakMode; -import com.evolveum.midpoint.common.refinery.*; -import com.evolveum.midpoint.notifications.api.transports.Message; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemName; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.*; -import com.evolveum.midpoint.schema.processor.*; -import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; -import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import com.evolveum.prism.xml.ns._public.types_3.RawType; - import org.apache.commons.lang.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -43,17 +24,28 @@ import org.testng.AssertJUnit; import org.testng.annotations.Test; +import com.evolveum.icf.dummy.resource.BreakMode; import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.midpoint.audit.api.AuditEventStage; import com.evolveum.midpoint.common.StaticExpressionUtil; +import com.evolveum.midpoint.common.refinery.*; import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.context.ModelContext; +import com.evolveum.midpoint.notifications.api.transports.Message; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.delta.*; +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.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.ObjectDeltaOperation; +import com.evolveum.midpoint.schema.SelectorOptions; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.internals.InternalCounters; import com.evolveum.midpoint.schema.internals.InternalMonitor; +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.MiscSchemaUtil; @@ -69,26 +61,13 @@ import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.PolicyViolationException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConstructionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.MappingType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectFactory; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceAttributeDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; +import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; +import com.evolveum.prism.xml.ns._public.types_3.RawType; + +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestModelServiceContract extends AbstractInitializedModelIntegrationTest { @@ -106,8 +85,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); InternalMonitor.reset(); -// InternalMonitor.setTraceShadowFetchOperation(true); -// InternalMonitor.setTraceResourceSchemaOperations(true); InternalMonitor.setTrace(InternalCounters.PRISM_OBJECT_CLONE_COUNT, true); // setGlobalTracingOverride(addNotificationsLogging(createModelLoggingTracingProfile())); @@ -115,8 +92,6 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test050GetUserJack() throws Exception { - final String TEST_NAME = "test050GetUserJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -136,8 +111,6 @@ public void test050GetUserJack() throws Exception { @Test public void test051GetUserBarbossa() throws Exception { - final String TEST_NAME = "test051GetUserBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -159,8 +132,6 @@ public void test051GetUserBarbossa() throws Exception { @Test public void test099ModifyUserAddAccountFailing() throws Exception { - final String TEST_NAME = "test099ModifyUserAddAccountFailing"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -204,17 +175,6 @@ public void test099ModifyUserAddAccountFailing() throws Exception { UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); -// // Check audit -// display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(2); -// dummyAuditService.assertSimpleRecordSanity(); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(3); -// dummyAuditService.asserHasDelta(ChangeType.MODIFY, UserType.class); -// dummyAuditService.asserHasDelta(ChangeType.ADD, ShadowType.class); -// dummyAuditService.assertTarget(USER_JACK_OID); -// dummyAuditService.assertExecutionSuccess(); - notificationManager.setDisabled(true); getDummyResource().resetBreakMode(); @@ -235,8 +195,6 @@ public void test099ModifyUserAddAccountFailing() throws Exception { @Test public void test100ModifyUserAddAccount() throws Exception { - final String TEST_NAME = "test100ModifyUserAddAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -310,22 +268,12 @@ public void test100ModifyUserAddAccount() throws Exception { Message message = messages.get(0); // number of messages was already checked assertEquals("Invalid list of recipients", Arrays.asList("recipient@evolveum.com"), message.getTo()); assertTrue("No account name in account password notification", message.getBody().contains("Password for account jack on Dummy Resource is:")); -// -// messages = dummyTransport.getMessages("dummy:newAccountsViaExpression"); -// assertNotNull("No messages recorded in dummy transport (expressions)", messages); -// assertEquals("Invalid number of messages recorded in dummy transport (expressions)", 1, messages.size()); -// message = messages.get(0); -// assertEquals("Invalid list of recipients (expressions)", Arrays.asList("test1", "test2"), message.getTo()); -// assertEquals("Invalid message subject", "Changed account for jack", message.getSubject()); -// assertEquals("Invalid message body", "Body: Changed account for jack", message.getBody()); assertSteadyResources(); } @Test public void test101GetAccount() throws Exception { - final String TEST_NAME = "test101GetAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -340,7 +288,7 @@ public void test101GetAccount() throws Exception { rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); // WHEN - PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, null , task, result); + PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); // THEN display("Account", account); @@ -364,10 +312,10 @@ public void test101GetAccount() throws Exception { "cold"); ResourceAttributeContainer attributesContainer = ShadowUtil.getAttributesContainer(account); - assertNotNull("No attribute container from "+account, attributesContainer); + assertNotNull("No attribute container from " + account, attributesContainer); Collection> identifiers = attributesContainer.getPrimaryIdentifiers(); - assertNotNull("No identifiers (null) in attributes container in "+accountJackOid, identifiers); - assertFalse("No identifiers (empty) in attributes container in "+accountJackOid, identifiers.isEmpty()); + assertNotNull("No identifiers (null) in attributes container in " + accountJackOid, identifiers); + assertFalse("No identifiers (empty) in attributes container in " + accountJackOid, identifiers.isEmpty()); ResourceAttribute fullNameAttr = attributesContainer.findAttribute(dummyResourceCtl.getAttributeFullnameQName()); PrismAsserts.assertPropertyValue(fullNameAttr, ACCOUNT_JACK_DUMMY_FULLNAME); @@ -388,14 +336,14 @@ public void test101GetAccount() throws Exception { public void test102GetAccountNoFetch() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test102GetAccountNoFetch"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); // WHEN - PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options , task, result); + PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options, task, result); display("Account", account); display("Account def", account.getDefinition()); @@ -414,14 +362,14 @@ public void test102GetAccountNoFetch() throws Exception { public void test103GetAccountRaw() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test103GetAccountRaw"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); // WHEN - PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options , task, result); + PrismObject account = modelService.getObject(ShadowType.class, accountJackOid, options, task, result); display("Account", account); display("Account def", account.getDefinition()); @@ -440,7 +388,7 @@ public void test103GetAccountRaw() throws Exception { public void test105SearchAccount() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test105SearchAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); // get weapon attribute definition @@ -471,7 +419,7 @@ public void test105SearchAccount() throws Exception { public void test106SearchAccountWithoutResourceSchema() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test106SearchAccountWithoutResourceSchema"); + Task task = getTestTask(); OperationResult result = task.getResult(); // create weapon attribute definition - NOT SUPPORTED, use only when you know what you're doing! @@ -497,7 +445,7 @@ public void test106SearchAccountWithoutResourceSchema() throws Exception { public void test108ModifyUserAddAccountAgain() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test108ModifyUserAddAccountAgain"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -542,8 +490,6 @@ public void test108ModifyUserAddAccountAgain() throws Exception { @Test public void test109ModifyUserAddAccountAgain() throws Exception { - final String TEST_NAME = "test109ModifyUserAddAccountAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -592,8 +538,6 @@ public void test109ModifyUserAddAccountAgain() throws Exception { @Test public void test110GetUserResolveAccount() throws Exception { - final String TEST_NAME = "test110GetUserResolveAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -604,7 +548,7 @@ public void test110GetUserResolveAccount() throws Exception { .build(); // WHEN - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options, task, result); // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); @@ -628,11 +572,8 @@ public void test110GetUserResolveAccount() throws Exception { assertSteadyResources(); } - @Test public void test111GetUserResolveAccountResource() throws Exception { - final String TEST_NAME = "test111GetUserResolveAccountResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -644,7 +585,7 @@ public void test111GetUserResolveAccountResource() throws Exception { .build(); // WHEN - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options, task, result); // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); @@ -673,8 +614,6 @@ public void test111GetUserResolveAccountResource() throws Exception { @Test public void test112GetUserResolveAccountNoFetch() throws Exception { - final String TEST_NAME = "test112GetUserResolveAccountNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -684,10 +623,10 @@ public void test112GetUserResolveAccountNoFetch() throws Exception { getOpts.setResolve(true); getOpts.setNoFetch(true); Collection> options = - SelectorOptions.createCollection(prismContext.toUniformPath(UserType.F_LINK_REF), getOpts); + SelectorOptions.createCollection(prismContext.toUniformPath(UserType.F_LINK_REF), getOpts); // WHEN - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options , task, result); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, options, task, result); // THEN assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); @@ -715,8 +654,6 @@ public void test112GetUserResolveAccountNoFetch() throws Exception { @Test public void test119ModifyUserDeleteAccount() throws Exception { - final String TEST_NAME = "test119ModifyUserDeleteAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -727,7 +664,8 @@ public void test119ModifyUserDeleteAccount() throws Exception { ObjectDelta userDelta = prismContext.deltaFactory().object() .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); + ReferenceDelta accountDelta = prismContext.deltaFactory().reference() + .createModificationDelete(UserType.F_LINK_REF, getUserDefinition(), account); userDelta.addModification(accountDelta); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); @@ -742,15 +680,16 @@ public void test119ModifyUserDeleteAccount() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); // Check accountRef - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + PrismObject userJack = + modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertUserJack(userJack); UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of linkRefs", 0, userJackType.getLinkRef().size()); // Check is shadow is gone try { - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, null, result); - AssertJUnit.fail("Shadow "+accountJackOid+" still exists"); + repositoryService.getObject(ShadowType.class, accountJackOid, null, result); + AssertJUnit.fail("Shadow " + accountJackOid + " still exists"); } catch (ObjectNotFoundException e) { // This is OK } @@ -760,7 +699,7 @@ public void test119ModifyUserDeleteAccount() throws Exception { assertDummyScriptsDelete(); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -787,10 +726,8 @@ public void test119ModifyUserDeleteAccount() throws Exception { @Test public void test120AddAccount() throws Exception { - final String TEST_NAME = "test120AddAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -801,7 +738,8 @@ public void test120AddAccount() throws Exception { // WHEN when(); - Collection> executeChanges = executeChanges(accountDelta, null, task, result); + Collection> executeChanges = + executeChanges(accountDelta, null, task, result); // THEN then(); @@ -812,19 +750,22 @@ public void test120AddAccount() throws Exception { accountJackOid = ObjectDeltaOperation.findProjectionDeltaOidInCollection(executeChanges); assertNotNull("No account OID in executed deltas", accountJackOid); // Check accountRef (should be none) - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + PrismObject userJack = + modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); assertUserJack(userJack); UserType userJackType = userJack.asObjectable(); assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, + PrismObject accountShadow = repositoryService.getObject( + ShadowType.class, accountJackOid, SelectorOptions.createCollection(GetOperationOptions.createRaw()), result); assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); assertEnableTimestampShadow(accountShadow, startTime, endTime); // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); + PrismObject accountModel = modelService.getObject( + ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); assertEnableTimestampShadow(accountModel, startTime, endTime); @@ -863,8 +804,6 @@ public void test120AddAccount() throws Exception { */ @Test public void test121ModifyUserAddAccountRef() throws Exception { - final String TEST_NAME = "test121ModifyUserAddAccountRef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -872,7 +811,9 @@ public void test121ModifyUserAddAccountRef() throws Exception { ObjectDelta userDelta = prismContext.deltaFactory().object() .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountJackOid); + ReferenceDelta accountDelta = + prismContext.deltaFactory().reference().createModificationAdd( + UserType.F_LINK_REF, getUserDefinition(), accountJackOid); userDelta.addModification(accountDelta); // WHEN @@ -894,7 +835,8 @@ public void test121ModifyUserAddAccountRef() throws Exception { assertDummyAccountShadowRepo(accountShadow, accountJackOid, "jack"); // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); + PrismObject accountModel = modelService.getObject( + ShadowType.class, accountJackOid, null, task, result); assertDummyAccountShadowModel(accountModel, accountJackOid, "jack", "Jack Sparrow"); // Check account in dummy resource @@ -924,13 +866,10 @@ public void test121ModifyUserAddAccountRef() throws Exception { assertSteadyResources(); } - - @Test public void test128ModifyUserDeleteAccountRef() throws Exception { - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test128ModifyUserDeleteAccountRef"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -995,9 +934,8 @@ public void test128ModifyUserDeleteAccountRef() throws Exception { @Test public void test129DeleteAccount() throws Exception { - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test129DeleteAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -1050,48 +988,46 @@ public void test129DeleteAccount() throws Exception { assertSteadyResources(); } - @Test public void test130PreviewModifyUserJackAssignAccount() { - // GIVEN - try{ - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test130PreviewModifyUserJackAssignAccount"); - OperationResult result = task.getResult(); - preTestCleanup(AssignmentPolicyEnforcementType.FULL); + try { + Task task = getTestTask(); + OperationResult result = task.getResult(); + preTestCleanup(AssignmentPolicyEnforcementType.FULL); - Collection> deltas = new ArrayList<>(); - ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); - deltas.add(accountAssignmentUserDelta); + Collection> deltas = new ArrayList<>(); + ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(USER_JACK_OID, RESOURCE_DUMMY_OID, null, true); + deltas.add(accountAssignmentUserDelta); - // WHEN - ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); + // WHEN + modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - // THEN - result.computeStatus(); - TestUtil.assertSuccess("previewChanges result", result); - assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); + // THEN + result.computeStatus(); + TestUtil.assertSuccess("previewChanges result", result); + assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - PrismObject userJack = getUser(USER_JACK_OID); - display("User after change execution", userJack); - assertUserJack(userJack); - // Check accountRef - assertUserNoAccountRefs(userJack); + PrismObject userJack = getUser(USER_JACK_OID); + display("User after change execution", userJack); + assertUserJack(userJack); + // Check accountRef + assertUserNoAccountRefs(userJack); - // TODO: assert context - // TODO: assert context - // TODO: assert context + // TODO: assert context + // TODO: assert context + // TODO: assert context - // We (temporarily?) turned off resource ref resolution during preview operation. - // It complicated things regarding objects immutability a bit. Let the clients resolve these references themselves. + // We (temporarily?) turned off resource ref resolution during preview operation. + // It complicated things regarding objects immutability a bit. Let the clients resolve these references themselves. - //assertResolvedResourceRefs(modelContext); + //assertResolvedResourceRefs(modelContext); - // Check account in dummy resource - assertNoDummyAccount("jack"); + // Check account in dummy resource + assertNoDummyAccount("jack"); - dummyAuditService.assertNoRecord(); - }catch(Exception ex){ + dummyAuditService.assertNoRecord(); + } catch (Exception ex) { logger.info("Exception {}", ex.getMessage(), ex); } @@ -1100,8 +1036,6 @@ public void test130PreviewModifyUserJackAssignAccount() { @Test public void test131ModifyUserJackAssignAccount() throws Exception { - final String TEST_NAME="test131ModifyUserJackAssignAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1181,8 +1115,6 @@ public void test131ModifyUserJackAssignAccount() throws Exception { */ @Test public void test132ModifyAccountJackDummy() throws Exception { - final String TEST_NAME = "test132ModifyAccountJackDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1272,8 +1204,6 @@ public void test132ModifyAccountJackDummy() throws Exception { */ @Test public void test135ModifyUserJackAssignAccountAgain() throws Exception { - final String TEST_NAME="test135ModifyUserJackAssignAccountAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1295,7 +1225,6 @@ public void test135ModifyUserJackAssignAccountAgain() throws Exception { accountJackOid = getSingleLinkOid(userJack); - // Check shadow PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountJackOid, SelectorOptions.createCollection(GetOperationOptions.createRaw()), result); @@ -1335,8 +1264,6 @@ public void test135ModifyUserJackAssignAccountAgain() throws Exception { @Test public void test136JackRecomputeNoChange() throws Exception { - final String TEST_NAME="test136JackRecomputeNoChange"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1397,8 +1324,6 @@ public void test136JackRecomputeNoChange() throws Exception { @Test public void test139ModifyUserJackUnassignAccount() throws Exception { - final String TEST_NAME = "test139ModifyUserJackUnassignAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1459,8 +1384,6 @@ public void test139ModifyUserJackUnassignAccount() throws Exception { */ @Test public void test141ModifyUserJackAssignAccountPositiveEnforcement() throws Exception { - final String TEST_NAME = "test141ModifyUserJackAssignAccountPositiveEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1543,8 +1466,6 @@ public void test141ModifyUserJackAssignAccountPositiveEnforcement() throws Excep */ @Test public void test148ModifyUserJackUnassignAccountPositiveEnforcement() throws Exception { - final String TEST_NAME = "test148ModifyUserJackUnassignAccountPositiveEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1638,8 +1559,6 @@ public void test148ModifyUserJackUnassignAccountPositiveEnforcement() throws Exc */ @Test public void test149ModifyUserJackDeleteAccount() throws Exception { - final String TEST_NAME = "test149ModifyUserJackDeleteAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1710,8 +1629,6 @@ public void test149ModifyUserJackDeleteAccount() throws Exception { */ @Test public void test151ModifyUserJackAssignAccountRelativeEnforcement() throws Exception { - final String TEST_NAME = "test151ModifyUserJackAssignAccountRelativeEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1787,11 +1704,8 @@ public void test151ModifyUserJackAssignAccountRelativeEnforcement() throws Excep */ @Test public void test158ModifyUserJackUnassignAccountRelativeEnforcement() throws Exception { - final String TEST_NAME = "test158ModifyUserJackUnassignAccountRelativeEnforcement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.RELATIVE); @@ -1851,8 +1765,6 @@ public void test158ModifyUserJackUnassignAccountRelativeEnforcement() throws Exc */ @Test public void test161ModifyUserJackAssignAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test161ModifyUserJackAssignAccountNoneEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1913,8 +1825,6 @@ public void test161ModifyUserJackAssignAccountNoneEnforcement() throws Exception @Test public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test163ModifyUserJackAddAccountNoneEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1926,9 +1836,10 @@ public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { .createEmptyModifyDelta(UserType.class, USER_JACK_OID); PrismReferenceValue accountRefVal = itemFactory().createReferenceValue(); accountRefVal.setObject(account); - ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); + ReferenceDelta accountDelta = prismContext.deltaFactory().reference() + .createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); dummyAuditService.clear(); dummyTransport.clearMessages(); @@ -1993,11 +1904,8 @@ public void test163ModifyUserJackAddAccountNoneEnforcement() throws Exception { @Test public void test164ModifyUserJackUnassignAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test164ModifyUserJackUnassignAccountNoneEnforcement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.NONE); @@ -2060,8 +1968,6 @@ public void test164ModifyUserJackUnassignAccountNoneEnforcement() throws Excepti @Test public void test169ModifyUserJackDeleteAccountNoneEnforcement() throws Exception { - final String TEST_NAME = "test169ModifyUserJackDeleteAccountNoneEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2127,8 +2033,6 @@ public void test169ModifyUserJackDeleteAccountNoneEnforcement() throws Exception @Test public void test180ModifyUserAddAccountFullEnforcement() throws Exception { - final String TEST_NAME = "test180ModifyUserAddAccountFullEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2142,7 +2046,7 @@ public void test180ModifyUserAddAccountFullEnforcement() throws Exception { accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); try { @@ -2188,8 +2092,6 @@ public void test180ModifyUserAddAccountFullEnforcement() throws Exception { @Test public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exception { - final String TEST_NAME = "test182ModifyUserAddAndAssignAccountPositiveEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2202,7 +2104,7 @@ public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exc accountRefVal.setObject(account); ReferenceDelta accountDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); @@ -2266,7 +2168,7 @@ public void test182ModifyUserAddAndAssignAccountPositiveEnforcement() throws Exc public void test189ModifyUserJackUnassignAndDeleteAccount() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test149ModifyUserJackUnassignAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); @@ -2316,13 +2218,11 @@ public void test189ModifyUserJackUnassignAndDeleteAccount() throws Exception { /** * We try to both assign an account and modify that account in one operation. - * Some changes should be reflected to account (e.g. weapon) as the mapping is weak, other should be - * overridded (e.g. fullname) as the mapping is strong. + * Some changes should be reflected to account (e.g. weapon) as the mapping is weak, + * other should be overridden (e.g. fullname) as the mapping is strong. */ @Test public void test190ModifyUserJackAssignAccountAndModify() throws Exception { - final String TEST_NAME = "test190ModifyUserJackAssignAccountAndModify"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2402,20 +2302,15 @@ public void test190ModifyUserJackAssignAccountAndModify() throws Exception { /** * We try to modify an assignment of the account and see whether changes will be recorded in the account itself. - * */ @Test public void test191ModifyUserJackModifyAssignment() throws Exception { - final String TEST_NAME = "test191ModifyUserJackModifyAssignment"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); Collection> deltas = new ArrayList<>(); - //PrismPropertyDefinition definition = getAssignmentDefinition().findPropertyDefinition(new QName(SchemaConstantsGenerated.NS_COMMON, "accountConstruction")); - PrismObject dummyResource = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); RefinedResourceSchema refinedSchema = RefinedResourceSchemaImpl.getRefinedSchema(dummyResource, prismContext); @@ -2498,7 +2393,6 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { DummyAccount dummyAccount = getDummyAccount(null, USER_JACK_USERNAME); display(dummyAccount.debugDump()); assertDummyAccountAttribute(null, USER_JACK_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "q"); - //assertEquals("Missing or incorrect attribute value", "soda", dummyAccount.getAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, String.class)); assertDummyScriptsModify(userJack, true); @@ -2520,8 +2414,6 @@ public void test191ModifyUserJackModifyAssignment() throws Exception { @Test public void test192ModifyUserJack() throws Exception { - final String TEST_NAME = "test192ModifyUserJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2592,8 +2484,6 @@ public void test192ModifyUserJack() throws Exception { @Test public void test193ModifyUserJackLocationEmpty() throws Exception { - final String TEST_NAME = "test193ModifyUserJackLocationEmpty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2658,8 +2548,6 @@ public void test193ModifyUserJackLocationEmpty() throws Exception { @Test public void test194ModifyUserJackLocationNull() throws Exception { - final String TEST_NAME = "test194ModifyUserJackLocationNull"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2667,7 +2555,7 @@ public void test194ModifyUserJackLocationNull() throws Exception { try { // WHEN - modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, (PolyString)null); + modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, task, result, (PolyString) null); AssertJUnit.fail("Unexpected success"); } catch (IllegalStateException e) { @@ -2691,8 +2579,6 @@ public void test194ModifyUserJackLocationNull() throws Exception { @Test public void test195ModifyUserJackLocationSea() throws Exception { - final String TEST_NAME = "test195ModifyUserJackLocationSea"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2760,13 +2646,13 @@ public void test195ModifyUserJackLocationSea() throws Exception { public void test198ModifyUserJackRaw() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test196ModifyUserJackRaw"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_JACK_OID, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Marvelous Captain Jack Sparrow")); - Collection> deltas = (Collection)MiscUtil.createCollection(objectDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(objectDelta); // WHEN modelService.executeChanges(deltas, ModelExecuteOptions.createRaw(), task, result); @@ -2813,7 +2699,7 @@ public void test198ModifyUserJackRaw() throws Exception { public void test199DeleteUserJack() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestModelServiceContract.class.getName() + ".test199DeleteUserJack"); + Task task = getTestTask(); OperationResult result = task.getResult(); preTestCleanup(AssignmentPolicyEnforcementType.FULL); @@ -2830,7 +2716,7 @@ public void test199DeleteUserJack() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); try { - PrismObject userJack = getUser(USER_JACK_OID); + getUser(USER_JACK_OID); AssertJUnit.fail("Jack is still alive!"); } catch (ObjectNotFoundException ex) { // This is OK @@ -2844,7 +2730,7 @@ public void test199DeleteUserJack() throws Exception { assertDummyScriptsDelete(); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -2873,8 +2759,6 @@ public void test199DeleteUserJack() throws Exception { @Test public void test200AddUserBlackbeardWithAccount() throws Exception { - final String TEST_NAME = "test200AddUserBlackbeardWithAccount"; - // GIVEN Task task = getTestTask(); // Use custom channel to trigger a special outbound mapping @@ -2883,7 +2767,7 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { preTestCleanup(AssignmentPolicyEnforcementType.POSITIVE); PrismObject user = PrismTestUtil.parseObject(new File(TEST_DIR, "user-blackbeard-account-dummy.xml")); - addAccountLinkRef(user,new File(TEST_DIR, "account-blackbeard-dummy.xml")); + addAccountLinkRef(user, new File(TEST_DIR, "account-blackbeard-dummy.xml")); ObjectDelta userDelta = DeltaFactory.Object.createAddDelta(user); Collection> deltas = MiscSchemaUtil.createCollection(userDelta); @@ -2921,7 +2805,7 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { // Check account in dummy resource assertDefaultDummyAccount("blackbeard", "Edward Teach", true); DummyAccount dummyAccount = getDummyAccount(null, "blackbeard"); - assertEquals("Wrong loot", (Integer)10000, dummyAccount.getAttributeValue("loot", Integer.class)); + assertEquals("Wrong loot", (Integer) 10000, dummyAccount.getAttributeValue("loot", Integer.class)); assertDummyScriptsAdd(userBlackbeard, accountModel, getDummyResourceType()); @@ -2937,7 +2821,7 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { // this one was redundant // dummyAuditService.assertExecutionDeltas(1, 1); // dummyAuditService.assertHasDelta(1, ChangeType.MODIFY, UserType.class); - // raw operation, no target + // raw operation, no target // dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); @@ -2958,8 +2842,6 @@ public void test200AddUserBlackbeardWithAccount() throws Exception { @Test public void test210AddUserMorganWithAssignment() throws Exception { - final String TEST_NAME = "test210AddUserMorganWithAssignment"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3010,7 +2892,7 @@ public void test210AddUserMorganWithAssignment() throws Exception { assertDummyScriptsAdd(userMorgan, accountModel, getDummyResourceType()); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -3039,8 +2921,6 @@ public void test210AddUserMorganWithAssignment() throws Exception { @Test public void test212RenameUserMorgan() throws Exception { - final String TEST_NAME = "test212RenameUserMorgan"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3079,7 +2959,7 @@ public void test212RenameUserMorgan() throws Exception { assertDummyScriptsModify(userMorgan); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -3088,7 +2968,7 @@ public void test212RenameUserMorgan() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); ObjectDeltaOperation auditShadowDelta = dummyAuditService.assertHasDelta(ChangeType.MODIFY, ShadowType.class); - assertEquals("Unexpected number of modifications in shadow audit delta: "+auditShadowDelta.debugDump(), 8, auditShadowDelta.getObjectDelta().getModifications().size()); + assertEquals("Unexpected number of modifications in shadow audit delta: " + auditShadowDelta.debugDump(), 8, auditShadowDelta.getObjectDelta().getModifications().size()); dummyAuditService.assertOldValue(ChangeType.MODIFY, UserType.class, UserType.F_NAME, PrismTestUtil.createPolyString("morgan")); @@ -3124,8 +3004,6 @@ public void test212RenameUserMorgan() throws Exception { */ @Test public void test240AddUserCharlesRaw() throws Exception { - final String TEST_NAME = "test240AddUserCharlesRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3156,7 +3034,7 @@ public void test240AddUserCharlesRaw() throws Exception { dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.ADD, UserType.class); - // raw operation, no target + // raw operation, no target // dummyAuditService.assertTarget(userAfter.getOid()); dummyAuditService.assertExecutionSuccess(); @@ -3168,8 +3046,6 @@ public void test240AddUserCharlesRaw() throws Exception { */ @Test public void test241DeleteUserCharlesRaw() throws Exception { - final String TEST_NAME = "test241DeleteUserCharlesRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3198,7 +3074,7 @@ public void test241DeleteUserCharlesRaw() throws Exception { dummyAuditService.assertAnyRequestDeltas(); dummyAuditService.assertExecutionDeltas(1); dummyAuditService.assertHasDelta(ChangeType.DELETE, UserType.class); - // raw operation, no target + // raw operation, no target // dummyAuditService.assertTarget(userCharlesOid); dummyAuditService.assertExecutionSuccess(); @@ -3207,8 +3083,6 @@ public void test241DeleteUserCharlesRaw() throws Exception { @Test public void test300AddUserJackWithAssignmentBlue() throws Exception { - final String TEST_NAME="test300AddUserJackWithAssignmentBlue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3276,8 +3150,6 @@ public void test300AddUserJackWithAssignmentBlue() throws Exception { */ @Test public void test302ModifyAccountJackDummyBlue() throws Exception { - final String TEST_NAME = "test302ModifyAccountJackDummyBlue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3315,7 +3187,7 @@ accountJackBlueOid, getDummyResourceController(RESOURCE_DUMMY_BLUE_NAME).getAttr // Check account // All the changes should be reflected to the account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountJackOid, null, task, result); + modelService.getObject(ShadowType.class, accountJackOid, null, task, result); assertAccountShadowRepo(accountShadow, accountJackBlueOid, USER_JACK_USERNAME, getDummyResourceType(RESOURCE_DUMMY_BLUE_NAME)); // Check account in dummy resource @@ -3387,7 +3259,7 @@ private void assertDummyScriptsAdd(PrismObject user, PrismObject user, PrismObject> accountSource = () -> { try { return PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); } catch (SchemaException | IOException e) { - throw new IllegalStateException(e.getMessage(),e); + throw new IllegalStateException(e.getMessage(), e); } }; ObjectChecker> checker = modelContext -> assertAddAccount(modelContext, false); - modifyUserAddAccountImplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountExplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSame(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSameReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqualReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqualReverse(TEST_NAME, accountSource, checker); + modifyUserAddAccountImplicit(accountSource, checker); + modifyUserAddAccountExplicit(accountSource, checker); + modifyUserAddAccountImplicitExplicitSame(accountSource, checker); + modifyUserAddAccountImplicitExplicitSameReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqual(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqualReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitNotEqual(accountSource); + modifyUserAddAccountImplicitExplicitNotEqualReverse(accountSource); } @Test public void test101ModifyUserAddAccountNoAttributesBundle() throws Exception { - final String TEST_NAME = "test101ModifyUserAddAccountNoAttributesBundle"; - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.NONE); ObjectSource> accountSource = new ObjectSource>() { @@ -117,8 +115,8 @@ public PrismObject get() { PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); account.removeContainer(ShadowType.F_ATTRIBUTES); return account; - } catch (SchemaException|IOException e) { - throw new IllegalStateException(e.getMessage(),e); + } catch (SchemaException | IOException e) { + throw new IllegalStateException(e.getMessage(), e); } } }; @@ -130,22 +128,20 @@ public void check(ModelContext modelContext) { } }; - modifyUserAddAccountImplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountExplicit(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSame(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitSameReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitEqualReverse(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqual(TEST_NAME, accountSource, checker); - modifyUserAddAccountImplicitExplicitNotEqualReverse(TEST_NAME, accountSource, checker); + modifyUserAddAccountImplicit(accountSource, checker); + modifyUserAddAccountExplicit(accountSource, checker); + modifyUserAddAccountImplicitExplicitSame(accountSource, checker); + modifyUserAddAccountImplicitExplicitSameReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqual(accountSource, checker); + modifyUserAddAccountImplicitExplicitEqualReverse(accountSource, checker); + modifyUserAddAccountImplicitExplicitNotEqual(accountSource); + modifyUserAddAccountImplicitExplicitNotEqualReverse(accountSource); } - private void modifyUserAddAccountImplicit(String bundleName, ObjectSource> accountSource, + private void modifyUserAddAccountImplicit(ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "Implicit"; - // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicit"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -161,12 +157,10 @@ private void modifyUserAddAccountImplicit(String bundleName, ObjectSource> accountSource, + private void modifyUserAddAccountExplicit(ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "Explicit"; - // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountExplicit"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -179,12 +173,11 @@ private void modifyUserAddAccountExplicit(String bundleName, ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitSame"; - + private void modifyUserAddAccountImplicitExplicitSame( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitSame"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -201,12 +194,11 @@ private void modifyUserAddAccountImplicitExplicitSame(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitSameReverse"; - + private void modifyUserAddAccountImplicitExplicitSameReverse( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitSameReverse"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -223,12 +215,11 @@ private void modifyUserAddAccountImplicitExplicitSameReverse(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitEqual"; - + private void modifyUserAddAccountImplicitExplicitEqual( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitEqual"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -245,12 +236,11 @@ private void modifyUserAddAccountImplicitExplicitEqual(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitEqualReverse(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitEqualReverse"; - + private void modifyUserAddAccountImplicitExplicitEqualReverse( + ObjectSource> accountSource, + ObjectChecker> checker) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitEqualReverse"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -267,12 +257,10 @@ private void modifyUserAddAccountImplicitExplicitEqualReverse(String bundleName, doPreview(deltas, checker, task, result); } - private void modifyUserAddAccountImplicitExplicitNotEqual(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitNotEqual"; - + private void modifyUserAddAccountImplicitExplicitNotEqual( + ObjectSource> accountSource) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitNotEqual"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -291,12 +279,10 @@ private void modifyUserAddAccountImplicitExplicitNotEqual(String bundleName, doPreviewFail(deltas, task, result); } - private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleName, - ObjectSource> accountSource, ObjectChecker> checker) throws Exception { - final String TEST_NAME = bundleName + "ImplicitExplicitNotEqualReverse"; - + private void modifyUserAddAccountImplicitExplicitNotEqualReverse( + ObjectSource> accountSource) throws Exception { // GIVEN - Task task = getTestTask(); + Task task = createPlainTask("modifyUserAddAccountImplicitExplicitNotEqualReverse"); OperationResult result = task.getResult(); PrismObject account = accountSource.get(); @@ -317,8 +303,8 @@ private void modifyUserAddAccountImplicitExplicitNotEqualReverse(String bundleNa private void doPreview(Collection> deltas, ObjectChecker> checker, Task task, OperationResult result) - throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, - ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { + throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, + ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { display("Input deltas: ", deltas); // WHEN @@ -331,15 +317,16 @@ private void doPreview(Collection> deltas, assertSuccess(result); } - private void doPreviewFail(Collection> deltas, Task task, OperationResult result) - throws SchemaException, PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, - ObjectAlreadyExistsException, CommunicationException, ConfigurationException, SecurityViolationException { + private void doPreviewFail( + Collection> deltas, Task task, OperationResult result) + throws PolicyViolationException, ExpressionEvaluationException, ObjectNotFoundException, + ObjectAlreadyExistsException, CommunicationException, ConfigurationException, + SecurityViolationException { display("Input deltas: ", deltas); try { // WHEN - ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); - + modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); AssertJUnit.fail("Expected exception, but it haven't come"); } catch (SchemaException e) { // This is expected @@ -355,7 +342,7 @@ private void assertAddAccount(ModelContext modelContext, boolean expec ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); assertSideEffectiveDeltasOnly(focusContext.getSecondaryDelta(), "focus secondary delta", ActivationStatusType.ENABLED); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -393,8 +380,6 @@ private void assertAddAccount(ModelContext modelContext, boolean expec @Test public void test130GetCompiledGuiProfile() throws Exception { - final String TEST_NAME = "test130GetCompiledGuiProfile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -406,11 +391,11 @@ public void test130GetCompiledGuiProfile() throws Exception { assertSuccess(result); assertCompiledGuiProfile(compiledGuiProfile) - .assertAdditionalMenuLinks(0) - .assertUserDashboardLinks(1) - .assertObjectForms(1) - .assertUserDashboardWidgets(0) - .assertObjectCollectionViews(3); + .assertAdditionalMenuLinks(0) + .assertUserDashboardLinks(1) + .assertObjectForms(1) + .assertUserDashboardWidgets(0) + .assertObjectCollectionViews(3); RichHyperlinkType link = compiledGuiProfile.getUserDashboardLink().get(0); assertEquals("Bad link label", "Foo", link.getLabel()); @@ -421,8 +406,6 @@ public void test130GetCompiledGuiProfile() throws Exception { @Test public void test150GetGuybrushRefinedObjectClassDef() throws Exception { - final String TEST_NAME = "test150GetGuybrushRefinedObjectClassDef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -445,8 +428,6 @@ public void test150GetGuybrushRefinedObjectClassDef() throws Exception { @Test public void test200ModifyUserGuybrushDeleteAccount() throws Exception { - final String TEST_NAME = "test200ModifyUserGuybrushDeleteAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -477,7 +458,7 @@ public void test200ModifyUserGuybrushDeleteAccount() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -494,8 +475,6 @@ public void test200ModifyUserGuybrushDeleteAccount() throws Exception { @Test public void test210GuybrushAddAccount() throws Exception { - final String TEST_NAME = "test210GuybrushAddAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -544,8 +523,6 @@ public void test210GuybrushAddAccount() throws Exception { @Test public void test212ModifyUserAddAccountRef() throws Exception { - final String TEST_NAME = "test212ModifyUserAddAccountRef"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -573,9 +550,8 @@ public void test212ModifyUserAddAccountRef() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -589,7 +565,7 @@ public void test212ModifyUserAddAccountRef() throws Exception { assertNull("Unexpected account primary delta", accountPrimaryDelta); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertEquals("Unexpected size of account secondary delta: "+accountSecondaryDelta, 2, accountSecondaryDelta.getModifications().size()); + assertEquals("Unexpected size of account secondary delta: " + accountSecondaryDelta, 2, accountSecondaryDelta.getModifications().size()); PrismAsserts.assertPropertyAdd(accountSecondaryDelta, dummyResourceCtl.getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME), "rum"); PrismAsserts.assertPropertyAdd(accountSecondaryDelta, @@ -601,8 +577,6 @@ public void test212ModifyUserAddAccountRef() throws Exception { */ @Test public void test220PreviewJackAssignRolePirate() throws Exception { - final String TEST_NAME = "test220PreviewJackAssignRolePirate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -628,8 +602,6 @@ public void test220PreviewJackAssignRolePirate() throws Exception { */ @Test public void test221PreviewJackAssignRolePirateReconcile() throws Exception { - final String TEST_NAME = "test221PreviewJackAssignRolePirateReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -637,7 +609,7 @@ public void test221PreviewJackAssignRolePirateReconcile() throws Exception { assertUserBefore(USER_JACK_OID) .links() - .assertNone(); + .assertNone(); ObjectDelta delta = createAssignmentAssignmentHolderDelta(UserType.class, USER_JACK_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); @@ -654,7 +626,7 @@ public void test221PreviewJackAssignRolePirateReconcile() throws Exception { assertPreviewJackAssignRolePirate(modelContext); } - private void assertPreviewJackAssignRolePirate(ModelContext modelContext) throws Exception { + private void assertPreviewJackAssignRolePirate(ModelContext modelContext) { display("Preview context", modelContext); assertNotNull("Null model context", modelContext); @@ -731,17 +703,14 @@ private void assertPreviewJackAssignRolePirate(ModelContext modelConte */ @Test public void test230GuybrushAssignAccountDummy() throws Exception { - final String TEST_NAME = "test230GuybrushAssignAccountDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); - ObjectDelta delta = createAssignmentAssignmentHolderDelta(UserType.class, USER_GUYBRUSH_OID, + createAssignmentAssignmentHolderDelta(UserType.class, USER_GUYBRUSH_OID, ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true); - - ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); + ModelExecuteOptions.createReconcile(); // WHEN when(); @@ -755,7 +724,7 @@ public void test230GuybrushAssignAccountDummy() throws Exception { accountGuybrushOid = assertUserAfter(USER_GUYBRUSH_OID) .singleLink() - .getOid(); + .getOid(); DummyAccount dummyAccount = assertDummyAccount(null, USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, true); display("Dummy account after", dummyAccount); @@ -768,8 +737,6 @@ public void test230GuybrushAssignAccountDummy() throws Exception { */ @Test public void test231PreviewGuybrushModifyAccountFullName() throws Exception { - final String TEST_NAME = "test231PreviewGuybrushModifyAccountFullName"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -820,8 +787,6 @@ public void test231PreviewGuybrushModifyAccountFullName() throws Exception { */ @Test public void test232PreviewGuybrushModifyAccountShip() throws Exception { - final String TEST_NAME = "test232PreviewGuybrushModifyAccountShip"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -871,8 +836,6 @@ public void test232PreviewGuybrushModifyAccountShip() throws Exception { */ @Test public void test233PreviewGuybrushAddRolePirate() throws Exception { - final String TEST_NAME = "test233PreviewGuybrushAddRolePirate"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -937,8 +900,6 @@ public void test233PreviewGuybrushAddRolePirate() throws Exception { */ @Test public void test234PreviewGuybrushAddRolePirateRecon() throws Exception { - final String TEST_NAME = "test234PreviewGuybrushAddRolePirateRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1005,8 +966,6 @@ public void test234PreviewGuybrushAddRolePirateRecon() throws Exception { */ @Test public void test236PreviewGuybrushAddRoleSailor() throws Exception { - final String TEST_NAME = "test236PreviewGuybrushAddRoleSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1058,8 +1017,6 @@ public void test236PreviewGuybrushAddRoleSailor() throws Exception { */ @Test public void test238PreviewGuybrushAddRoleSailorOwner() throws Exception { - final String TEST_NAME = "test238PreviewGuybrushAddRoleSailorOwner"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1095,8 +1052,6 @@ public void test238PreviewGuybrushAddRoleSailorOwner() throws Exception { @Test public void test239GuybrushUnAssignAccountDummy() throws Exception { - final String TEST_NAME = "test239GuybrushUnAssignAccountDummy"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1120,8 +1075,6 @@ public void test239GuybrushUnAssignAccountDummy() throws Exception { */ @Test public void test240GuybrushAssignAccountDummyRelative() throws Exception { - final String TEST_NAME = "test240GuybrushAssignAccountDummyRelative"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1148,8 +1101,6 @@ public void test240GuybrushAssignAccountDummyRelative() throws Exception { */ @Test public void test242PreviewGuybrushAddRolePirateRelative() throws Exception { - final String TEST_NAME = "test242PreviewGuybrushAddRolePirateRelative"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1215,8 +1166,6 @@ public void test242PreviewGuybrushAddRolePirateRelative() throws Exception { */ @Test public void test244PreviewGuybrushAddRolePirateRelativeRecon() throws Exception { - final String TEST_NAME = "test244PreviewGuybrushAddRolePirateRelativeRecon"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1279,8 +1228,6 @@ public void test244PreviewGuybrushAddRolePirateRelativeRecon() throws Exception @Test public void test249GuybrushUnAssignAccountDummyRelative() throws Exception { - final String TEST_NAME = "test249GuybrushUnAssignAccountDummyRelative"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1298,7 +1245,6 @@ public void test249GuybrushUnAssignAccountDummyRelative() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_RELATIVE_NAME, USER_GUYBRUSH_USERNAME); } - private void assertAccountDefaultDummyAttributeModify(ObjectDelta accountDelta, String attrName, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { @@ -1317,14 +1263,13 @@ private void assertAccountItemModify(ObjectDelta accountDelta, ItemPath itemPath, T[] expectedOldValues, T[] expectedAddValues, T[] expectedDeleteValues, T[] expectedReplaceValues) { PropertyDelta attrDelta = accountDelta.findPropertyDelta(itemPath); - assertNotNull("No delta for "+itemPath+" in "+accountDelta, attrDelta); + assertNotNull("No delta for " + itemPath + " in " + accountDelta, attrDelta); PrismAsserts.assertPropertyDelta(attrDelta, expectedOldValues, expectedAddValues, expectedDeleteValues, expectedReplaceValues); } // MAPPING TESTS // following tests mostly check correct functions of mappings - // the test3xx is testing mappings with default dummy resource. It has NORMAL mappings. /** @@ -1332,8 +1277,6 @@ private void assertAccountItemModify(ObjectDelta accountDelta, */ @Test public void test300ModifyElaineAccountDummyReplace() throws Exception { - final String TEST_NAME = "test300ModifyElaineAccountDummyReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1357,9 +1300,8 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContolle ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -1379,7 +1321,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContolle "Elaine Threepwood"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } /** @@ -1387,8 +1329,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_OID, getDummyResourceObject(), DummyResourceContolle */ @Test public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { - final String TEST_NAME = "test301ModifyElaineAccountDummyDeleteAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1414,9 +1354,8 @@ public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); - ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", focusContext.getSecondaryDelta()); Collection projectionContexts = modelContext.getProjectionContexts(); @@ -1437,7 +1376,7 @@ public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { getDummyResourceController().getAttributePath(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME), "Elaine Marley"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } /** @@ -1447,8 +1386,6 @@ public void test301ModifyElaineAccountDummyDeleteAdd() throws Exception { */ @Test public void test400ModifyElaineAccountDummyRedReplace() throws Exception { - final String TEST_NAME = "test400ModifyElaineAccountDummyRedReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1465,7 +1402,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, getDummyResourceObject(RESOURCE_DUMMY_RED_N ModelContext modelContext = modelInteractionService.previewChanges(deltas, new ModelExecuteOptions(), task, result); // THEN - then(); + then(); display("Preview context", modelContext); assertPartialError(result); } @@ -1477,8 +1414,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_RED_OID, getDummyResourceObject(RESOURCE_DUMMY_RED_N */ @Test public void test401ModifyElaineAccountDummyRedDeleteAdd() throws Exception { - final String TEST_NAME = "test401ModifyElaineAccountDummyRedDeleteAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1498,8 +1433,8 @@ public void test401ModifyElaineAccountDummyRedDeleteAdd() throws Exception { display("Preview context", modelContext); // THEN - then(); - assertPartialError(result); + then(); + assertPartialError(result); } // the test5xx is testing mappings with blue dummy resource. It has WEAK mappings. @@ -1509,8 +1444,6 @@ public void test401ModifyElaineAccountDummyRedDeleteAdd() throws Exception { */ @Test public void test500ModifyElaineAccountDummyBlueReplace() throws Exception { - final String TEST_NAME = "test500ModifyElaineAccountDummyBlueReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1534,7 +1467,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); @@ -1556,7 +1489,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE "Elaine Threepwood"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } /** @@ -1564,8 +1497,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE */ @Test public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { - final String TEST_NAME = "test501ModifyElaineAccountDummyBlueDeleteAdd"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1593,7 +1524,7 @@ public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); @@ -1618,17 +1549,14 @@ public void test501ModifyElaineAccountDummyBlueDeleteAdd() throws Exception { "Elaine Marley"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); } - /** * Changing USER fullName (replace delta), no account changes. */ @Test public void test600ModifyElaineUserDummyReplace() throws Exception { - final String TEST_NAME = "test600ModifyElaineUserDummyReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1655,7 +1583,7 @@ public void test600ModifyElaineUserDummyReplace() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); + assertNotNull("No focus primary delta: " + userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertModifications(userPrimaryDelta, 1); PrismAsserts.assertPropertyReplace(userPrimaryDelta, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); @@ -1719,8 +1647,6 @@ public void test600ModifyElaineUserDummyReplace() throws Exception { */ @Test public void test610ModifyElaineUserAccountDummyReplace() throws Exception { - final String TEST_NAME = "test610ModifyElaineUserAccountDummyReplace"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1758,7 +1684,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); + assertNotNull("No focus primary delta: " + userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertModifications(userPrimaryDelta, 1); PrismAsserts.assertPropertyReplace(userPrimaryDelta, UserType.F_FULL_NAME, PrismTestUtil.createPolyString("Elaine Threepwood")); @@ -1783,7 +1709,7 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE "Elaine LeChuck"); ObjectDelta accountSecondaryDelta = accContext.getSecondaryDelta(); - assertNull("Unexpected account secondary delta: "+accountSecondaryDelta, accountSecondaryDelta); + assertNull("Unexpected account secondary delta: " + accountSecondaryDelta, accountSecondaryDelta); // RED dummy resource: strong mappings accContext = modelContext.findProjectionContext( @@ -1822,8 +1748,6 @@ ACCOUNT_SHADOW_ELAINE_DUMMY_BLUE_OID, getDummyResourceObject(RESOURCE_DUMMY_BLUE @Test public void test620AddUserCapsize() throws Exception { - final String TEST_NAME = "test620AddUserCapsize"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1912,8 +1836,6 @@ public void test620AddUserCapsize() throws Exception { // testing multiple resources with dependencies (dummy -> dummy lemon) @Test public void test630AddUserRogers() throws Exception { - final String TEST_NAME = "test630AddUserRogers"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1938,7 +1860,7 @@ public void test630AddUserRogers() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); ObjectDelta userPrimaryDelta = focusContext.getPrimaryDelta(); - assertNotNull("No focus primary delta: "+userPrimaryDelta, userPrimaryDelta); + assertNotNull("No focus primary delta: " + userPrimaryDelta, userPrimaryDelta); PrismAsserts.assertIsAdd(userPrimaryDelta); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); @@ -2009,8 +1931,6 @@ public void test630AddUserRogers() throws Exception { */ @Test public void test700DisableElaineAccountTwoResources() throws Exception { - final String TEST_NAME = "test700DisableElaineAccountTwoResources"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2035,7 +1955,7 @@ public void test700DisableElaineAccountTwoResources() throws Exception { ModelElementContext focusContext = modelContext.getFocusContext(); assertNotNull("Null model focus context", focusContext); - assertNull("Unexpected focus primary delta: "+focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); + assertNull("Unexpected focus primary delta: " + focusContext.getPrimaryDelta(), focusContext.getPrimaryDelta()); ObjectDelta userSecondaryDelta = focusContext.getSecondaryDelta(); assertSideEffectiveDeltasOnly("focus secondary delta", userSecondaryDelta); @@ -2085,8 +2005,6 @@ public void test700DisableElaineAccountTwoResources() throws Exception { */ @Test public void test710PreviewGuybrushHavingRoleSailorOwner() throws Exception { - final String TEST_NAME = "test710PreviewGuybrushHavingRoleSailorOwner"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2121,5 +2039,4 @@ public void test710PreviewGuybrushHavingRoleSailorOwner() throws Exception { assertEquals("Wrong # of zero-set roles in evaluated assignment", 1, evaluatedAssignment.getRoles().getZeroSet().size()); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java index b8156f99141..74213b57f22 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestRaceConditions.java @@ -13,7 +13,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.test.annotation.DirtiesContext; @@ -26,10 +25,6 @@ import static org.testng.AssertJUnit.*; -/** - * @author mederly - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRaceConditions extends AbstractInitializedModelIntegrationTest { @@ -50,8 +45,6 @@ protected ConflictResolutionActionType getDefaultConflictResolutionAction() { @Test public void test100AssignRoles() throws Exception { - final String TEST_NAME="test100AssignRoles"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -91,10 +84,8 @@ public void test100AssignRoles() throws Exception { */ @Test public void test110UnassignRoles() throws Exception { - final String TEST_NAME = "test110UnassignRoles"; - // GIVEN - Task task = taskManager.createTaskInstance(TestRaceConditions.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userJack = getUser(USER_JACK_OID); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java index 1724860ba06..f194690b17e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestSchemalessResource.java @@ -8,8 +8,6 @@ import static org.testng.AssertJUnit.assertNotNull; -import javax.xml.bind.JAXBException; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -25,30 +23,22 @@ * Test if a resource without a schema can pass basic operations such as getObject and testResource. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSchemalessResource extends AbstractInitializedModelIntegrationTest { - private static String accountOid; - - public TestSchemalessResource() throws JAXBException { - super(); - } - /** * Just test if this does not die on an exception. */ @Test public void test001GetObject() throws Exception { - final String TEST_NAME = "test001GetObject"; - Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_OID, null, task, result); + PrismObject resource = modelService.getObject( + ResourceType.class, RESOURCE_DUMMY_SCHEMALESS_OID, null, task, result); // THEN assertNotNull("Null resource returned", resource); @@ -56,8 +46,6 @@ public void test001GetObject() throws Exception { @Test public void test002TestConnection() throws Exception { - final String TEST_NAME = "test002TestConnection"; - Task task = getTestTask(); // WHEN @@ -72,7 +60,5 @@ public void test002TestConnection() throws Exception { assertSuccess(connectorResult); assertTestResourceFailure(testResult, ConnectorTestOperation.RESOURCE_SCHEMA); assertFailure(testResult); - } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java index a4db2de84f1..b3b5f34a650 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestScriptHooks.java @@ -10,31 +10,24 @@ import java.io.File; -import com.evolveum.midpoint.model.intest.util.StaticHookRecorder; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; import com.evolveum.icf.dummy.resource.DummyResource; +import com.evolveum.midpoint.model.intest.util.StaticHookRecorder; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ChangeType; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { @@ -43,13 +36,10 @@ public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { protected static final File RESOURCE_DUMMY_HOOK_FILE = new File(TEST_DIR, "resource-dummy-hook.xml"); protected static final String RESOURCE_DUMMY_HOOK_OID = "10000000-0000-0000-0000-000004444001"; protected static final String RESOURCE_DUMMY_HOOK_NAME = "hook"; - protected static final String RESOURCE_DUMMY_HOOK_NAMESPACE = MidPointConstants.NS_RI; private static final File ORG_TOP_FILE = new File(TEST_DIR, "org-top.xml"); - private static final String ORG_TOP_OID = "80808080-8888-6666-0000-100000000001"; private static final File GENERIC_BLACK_PEARL_FILE = new File(TEST_DIR, "generic-blackpearl.xml"); - private static final String GENERIC_BLACK_PEARL_OID = "54195419-5419-5419-5419-000000000001"; private static final File SYSTEM_CONFIGURATION_HOOKS_FILE = new File(TEST_DIR, "system-configuration-hooks.xml"); @@ -59,14 +49,15 @@ public class TestScriptHooks extends AbstractInitializedModelIntegrationTest { protected PrismObject resourceDummyHook; @Override - public void initSystem(Task initTask, OperationResult initResult) - throws Exception { + public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - dummyResourceCtlHook = DummyResourceContoller.create(RESOURCE_DUMMY_HOOK_NAME, resourceDummyHook); + dummyResourceCtlHook = DummyResourceContoller.create( + RESOURCE_DUMMY_HOOK_NAME, resourceDummyHook); dummyResourceCtlHook.extendSchemaPirate(); dummyResourceHook = dummyResourceCtlHook.getDummyResource(); - resourceDummyHook = importAndGetObjectFromFile(ResourceType.class, RESOURCE_DUMMY_HOOK_FILE, RESOURCE_DUMMY_HOOK_OID, initTask, initResult); + resourceDummyHook = importAndGetObjectFromFile(ResourceType.class, + RESOURCE_DUMMY_HOOK_FILE, RESOURCE_DUMMY_HOOK_OID, initTask, initResult); resourceDummyHookType = resourceDummyHook.asObjectable(); dummyResourceCtlHook.setResource(resourceDummyHook); @@ -79,14 +70,10 @@ protected File getSystemConfigurationFile() { return SYSTEM_CONFIGURATION_HOOKS_FILE; } - - @Test public void test100JackAssignHookAccount() throws Exception { - final String TEST_NAME = "test100JackAssignHookAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestScriptHooks.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); dummyAuditService.clear(); @@ -136,10 +123,8 @@ public void test100JackAssignHookAccount() throws Exception { @Test public void test110JackAddOrganization() throws Exception { - final String TEST_NAME = "test110JackAddOrganization"; - // GIVEN - Task task = taskManager.createTaskInstance(TestScriptHooks.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); dummyAuditService.clear(); @@ -180,18 +165,5 @@ public void test110JackAddOrganization() throws Exception { StaticHookRecorder.assertInvocationCount("foo", 10); StaticHookRecorder.assertInvocationCount("bar", 10); StaticHookRecorder.assertInvocationCount("bar-user", 1); - - - // TODO -// // Check audit -// display("Audit", dummyAuditService); -// dummyAuditService.assertRecords(4); -// dummyAuditService.assertAnyRequestDeltas(); -// dummyAuditService.assertExecutionDeltas(1,1); -// dummyAuditService.asserHasDelta(1,ChangeType.ADD, OrgType.class); -// dummyAuditService.assertExecutionDeltas(3,1); -// dummyAuditService.asserHasDelta(3,ChangeType.MODIFY, UserType.class); -// dummyAuditService.assertExecutionSuccess(); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java index b4fa08c557f..7eda05a597a 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestTolerantAttributes.java @@ -6,19 +6,13 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.Collection; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; import org.apache.commons.lang.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -29,23 +23,21 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestTolerantAttributes extends AbstractInitializedModelIntegrationTest { - public static final File TEST_DIR = new File("src/test/resources/tolerant"); private static final String ACCOUNT_JACK_DUMMY_BLACK_FILENAME = "src/test/resources/common/account-jack-dummy-black.xml"; @@ -57,7 +49,7 @@ public class TestTolerantAttributes extends AbstractInitializedModelIntegrationT public void test100ModifyUserAddAccount() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test100ModifyUserAddAccount"); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -70,7 +62,7 @@ public void test100ModifyUserAddAccount() throws Exception { ReferenceDelta accountDelta = prismContext.deltaFactory().reference() .createModificationAdd(UserType.F_LINK_REF, getUserDefinition(), accountRefVal); userDelta.addModification(accountDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); @@ -111,7 +103,7 @@ public void test100ModifyUserAddAccount() throws Exception { // Check account in dummy resource assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - } + } /** * We are trying to add value to the resource (through a mapping). This value matches @@ -120,8 +112,6 @@ public void test100ModifyUserAddAccount() throws Exception { */ @Test public void test101ModifyAddAttributesIntolerantPattern() throws Exception { - final String TEST_NAME = "test101ModifyAddAttributesIntolerantPattern"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -133,7 +123,7 @@ public void test101ModifyAddAttributesIntolerantPattern() throws Exception { UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DESCRIPTION), "This value will be not added"); userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); // WHEN when(); @@ -165,150 +155,148 @@ UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DE } @Test - public void test102modifyAddAttributeTolerantPattern() throws Exception{ + public void test102modifyAddAttributeTolerantPattern() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test102modifyAddAttributeTolerantPattern"); - OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationAddProperty(UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DESCRIPTION), "res-thiIsOk"); - userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); - - modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); - - result.computeStatus(); - TestUtil.assertSuccess(result); - - // Check value in "quote attribute" - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - assertUserJack(userJack); - UserType userJackType = userJack.asObjectable(); - assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); - accountOid = accountRefType.getOid(); - assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); - assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); - assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - - // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); - assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account in dummy resource - assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - - // Check value of quote attribute - assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "quote", "res-thiIsOk"); + Task task = getTestTask(); + OperationResult result = task.getResult(); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); + + ObjectDelta userDelta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(UserType.class, USER_JACK_OID); + PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationAddProperty(UserType.F_DESCRIPTION, getUserDefinition().findPropertyDefinition(UserType.F_DESCRIPTION), "res-thiIsOk"); + userDelta.addModification(propertyDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); + + modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); + + result.computeStatus(); + TestUtil.assertSuccess(result); + + // Check value in "quote attribute" + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + assertUserJack(userJack); + UserType userJackType = userJack.asObjectable(); + assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); + ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); + accountOid = accountRefType.getOid(); + assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); + assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); + assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); + + // Check shadow + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); + assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account + PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); + assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account in dummy resource + assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); + + // Check value of quote attribute + assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "quote", "res-thiIsOk"); } @Test - public void test103modifyReplaceAttributeIntolerant() throws Exception{ + public void test103modifyReplaceAttributeIntolerant() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test103modifyReplaceAttributeIntolerant"); - OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); + Task task = getTestTask(); + OperationResult result = task.getResult(); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "gossip-thiIsNotOk"); - userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + ObjectDelta userDelta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(UserType.class, USER_JACK_OID); + PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "gossip-thiIsNotOk"); + userDelta.addModification(propertyDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); - modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); + modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); - result.computeStatus(); - TestUtil.assertSuccess(result); + result.computeStatus(); + TestUtil.assertSuccess(result); - // Check value in "quote attribute" - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + // Check value in "quote attribute" + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); // assertUserJack(userJack); - UserType userJackType = userJack.asObjectable(); - assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); - accountOid = accountRefType.getOid(); - assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); - assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); - assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - - // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); - assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account in dummy resource - assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - - // Check value of drink attribute - assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", null); + UserType userJackType = userJack.asObjectable(); + assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); + ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); + accountOid = accountRefType.getOid(); + assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); + assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); + assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); + + // Check shadow + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); + assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account + PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); + assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account in dummy resource + assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); + + // Check value of drink attribute + assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", null); } @Test - public void test104modifyReplaceAttributeTolerantPattern() throws Exception{ + public void test104modifyReplaceAttributeTolerantPattern() throws Exception { // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test104modifyReplaceAttributeTolerantPattern"); - OperationResult result = task.getResult(); - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); + Task task = getTestTask(); + OperationResult result = task.getResult(); + assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); - ObjectDelta userDelta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(UserType.class, USER_JACK_OID); - ItemPath drinkItemPath = ItemPath.create(new QName(getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME).getNamespace(), "drink")); - PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "thiIsOk"); - userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + ObjectDelta userDelta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(UserType.class, USER_JACK_OID); + ItemPath drinkItemPath = ItemPath.create(new QName(getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME).getNamespace(), "drink")); + PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationReplaceProperty(UserType.F_EMPLOYEE_NUMBER, getUserDefinition(), "thiIsOk"); + userDelta.addModification(propertyDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); - modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); + modelService.executeChanges(deltas, ModelExecuteOptions.createReconcile(), task, result); - result.computeStatus(); - TestUtil.assertSuccess(result); + result.computeStatus(); + TestUtil.assertSuccess(result); - // Check value in "quote attribute" - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + // Check value in "quote attribute" + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); // assertUserJack(userJack); - UserType userJackType = userJack.asObjectable(); - assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); - ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); - accountOid = accountRefType.getOid(); - assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); - PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); - assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); - assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); - - // Check shadow - PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); - assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account - PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); - assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); - - // Check account in dummy resource - assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); - - // Check value of drink attribute - assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", "thiIsOk"); + UserType userJackType = userJack.asObjectable(); + assertEquals("Unexpected number of accountRefs", 1, userJackType.getLinkRef().size()); + ObjectReferenceType accountRefType = userJackType.getLinkRef().get(0); + accountOid = accountRefType.getOid(); + assertFalse("No accountRef oid", StringUtils.isBlank(accountOid)); + PrismReferenceValue accountRefValue = accountRefType.asReferenceValue(); + assertEquals("OID mismatch in accountRefValue", accountOid, accountRefValue.getOid()); + assertNull("Unexpected object in accountRefValue", accountRefValue.getObject()); + + // Check shadow + PrismObject accountShadow = repositoryService.getObject(ShadowType.class, accountOid, null, result); + assertAccountShadowRepo(accountShadow, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account + PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); + assertAccountShadowModel(accountModel, accountOid, "jack", getDummyResourceType(RESOURCE_DUMMY_BLACK_NAME)); + + // Check account in dummy resource + assertAccount(userJack, RESOURCE_DUMMY_BLACK_OID); + + // Check value of drink attribute + assertDummyAccountAttribute(RESOURCE_DUMMY_BLACK_NAME, "jack", "gossip", "thiIsOk"); } @Test public void test105ModifyAddNonTolerantAttribute() throws Exception { - final String TEST_NAME = "test105ModifyAddNonTolerantAttribute"; - // GIVEN - Task task = taskManager.createTaskInstance(TestTolerantAttributes.class.getName() + ".test105modifyAddNonTolerantAttribute"); + Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -319,7 +307,7 @@ public void test105ModifyAddNonTolerantAttribute() throws Exception { assertNotNull("null definition for drink attribute ", accountDefinition.findPropertyDefinition(drinkItemPath)); PropertyDelta propertyDelta = prismContext.deltaFactory().property().createModificationAddProperty(drinkItemPath, accountDefinition.findPropertyDefinition(drinkItemPath), "This should be ignored"); userDelta.addModification(propertyDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(userDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(userDelta); // WHEN when(); @@ -329,6 +317,4 @@ public void test105ModifyAddNonTolerantAttribute() throws Exception { then(); assertPartialError(result); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java index fcdffed8f4c..72affd824b7 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java @@ -6,24 +6,15 @@ */ package com.evolveum.midpoint.model.intest; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.ItemFactory; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.test.TestResource; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - import org.apache.commons.lang3.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -35,8 +26,14 @@ import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.model.common.expression.evaluator.GenerateExpressionEvaluator; import com.evolveum.midpoint.model.impl.trigger.RecomputeTriggerHandler; +import com.evolveum.midpoint.prism.ItemFactory; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismValue; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; @@ -48,21 +45,17 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.TestResource; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { @@ -96,6 +89,8 @@ public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { private static final String CANNIBAL_PINEAPPLENOSE_USERNAME = "pineapplenose"; private static final String CANNIBAL_POTATOLEG_USERNAME = "potatoleg"; + private static final long DAY_MILLIS = 24 * 60 * 60 * 1000L; + private static String jackEmployeeNumber; private XMLGregorianCalendar funeralTimestamp; @@ -156,14 +151,14 @@ public void test000Sanity() throws Exception { private void assertObjectTemplate(List defaultObjectPolicyConfigurations, QName objectType, String subtype, String userTemplateOid) { - for (ObjectPolicyConfigurationType objectPolicyConfiguration: defaultObjectPolicyConfigurations) { + for (ObjectPolicyConfigurationType objectPolicyConfiguration : defaultObjectPolicyConfigurations) { if (MiscUtil.equals(objectPolicyConfiguration.getType(), objectType) && MiscUtil.equals(objectPolicyConfiguration.getSubtype(), subtype) && MiscUtil.equals(objectPolicyConfiguration.getObjectTemplateRef().getOid(), userTemplateOid)) { return; } } - AssertJUnit.fail("Object template for "+objectType+":"+subtype+"="+userTemplateOid+" not found"); + AssertJUnit.fail("Object template for " + objectType + ":" + subtype + "=" + userTemplateOid + " not found"); } @Test @@ -618,7 +613,7 @@ public void test149UnAssignDummy() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @@ -653,7 +648,6 @@ public void test150ModifyJackOrganizationalUnitRum() throws Exception { assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @Test @@ -687,7 +681,6 @@ public void test151ModifyJackOrganizationalUnitOffense() throws Exception { assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @Test @@ -724,7 +717,6 @@ public void test152ModifyJackOrganizationalUnitAddRum() throws Exception { assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); } @Test @@ -756,8 +748,7 @@ public void test153ModifyJackOrganizationalUnitDeleteOffense() throws Exception assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } /** @@ -795,8 +786,7 @@ public void test155ModifyJackOrganizationalUnitFD001() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } /** @@ -834,7 +824,7 @@ public void test156ReconcileJack() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } /** @@ -876,8 +866,7 @@ public void test157ModifyJackOrganizationalUnitFD0023() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } @Test @@ -917,8 +906,7 @@ public void test159ModifyJackDeleteOrganizationalUnitFD002() throws Exception { assertEquals("Wrong costCenter", "X000", userJackType.getCostCenter()); assertEquals("Wrong employee number", jackEmployeeNumber, userJackType.getEmployeeNumber()); assertEquals("Wrong telephone number", "1 222 3456789", userJackType.getTelephoneNumber()); - assertNull("Unexpected title: "+userJackType.getTitle(), userJackType.getTitle()); -// IntegrationTestTools.assertNoExtensionProperty(userJack, PIRACY_COLORS); + assertNull("Unexpected title: " + userJackType.getTitle(), userJackType.getTitle()); } @Test @@ -951,8 +939,10 @@ public void test160ModifyUserGivenNameAgain() throws Exception { dummyAuditService.assertHasDelta(ChangeType.MODIFY, UserType.class); dummyAuditService.assertTarget(USER_JACK_OID); dummyAuditService.assertExecutionSuccess(); - ObjectDeltaOperation objectDeltaOperation = dummyAuditService.getExecutionDelta(0, ChangeType.MODIFY, UserType.class); - assertEquals("unexpected number of modifications in audited delta", 10, objectDeltaOperation.getObjectDelta().getModifications().size()); // givenName + badLuck + modifyTimestamp + ObjectDeltaOperation objectDeltaOperation = + dummyAuditService.getExecutionDelta(0, ChangeType.MODIFY, UserType.class); + assertEquals("unexpected number of modifications in audited delta", + 10, objectDeltaOperation.getObjectDelta().getModifications().size()); // givenName + badLuck + modifyTimestamp PropertyDelta badLuckDelta = objectDeltaOperation.getObjectDelta().findPropertyDelta( ItemPath.create(UserType.F_EXTENSION, PIRACY_BAD_LUCK)); assertNotNull("badLuck delta was not found", badLuckDelta); @@ -960,8 +950,8 @@ public void test160ModifyUserGivenNameAgain() throws Exception { List oldValues = (List) badLuckDelta.getEstimatedOldValues(); assertNotNull("badLuck delta has null estimatedOldValues field", oldValues); ItemFactory factory = prismContext.itemFactory(); - PrismAsserts.assertEqualsCollectionUnordered("badLuck delta has wrong estimatedOldValues", oldValues, - factory.createPropertyValue(123L), factory.createPropertyValue(456L)); + PrismAsserts.assertEqualsCollectionUnordered("badLuck delta has wrong estimatedOldValues", + oldValues, factory.createPropertyValue(123L), factory.createPropertyValue(456L)); } @Test @@ -970,14 +960,16 @@ public void test162ModifyUserGivenNameAgainPhantomChange() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_JACK_OID, null, task, result); display("User before", userBefore); dummyAuditService.clear(); Collection> deltas = new ArrayList<>(); - ObjectDelta userDelta = prismContext.deltaFactory().object().createModificationReplaceProperty(UserType.class, - USER_JACK_OID, UserType.F_GIVEN_NAME, new PolyString("JACKIE")); // this is a phantom change + ObjectDelta userDelta = + prismContext.deltaFactory().object().createModificationReplaceProperty( + UserType.class, USER_JACK_OID, UserType.F_GIVEN_NAME, new PolyString("JACKIE")); // this is a phantom change deltas.add(userDelta); // WHEN @@ -1030,17 +1022,21 @@ public void test165ModifyUserGivenNameAgainAgain() throws Exception { PrismAsserts.assertNoItem(userJack, ItemPath.create(UserType.F_EXTENSION, PIRACY_BAD_LUCK)); } - private PrismObject assertOnDemandOrgExists(String orgName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private PrismObject assertOnDemandOrgExists(String orgName) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject org = findObjectByName(OrgType.class, orgName); - assertNotNull("The org "+orgName+" is missing!", org); - display("Org "+orgName, org); + assertNotNull("The org " + orgName + " is missing!", org); + display("Org " + orgName, org); PrismAsserts.assertPropertyValue(org, OrgType.F_NAME, PrismTestUtil.createPolyString(orgName)); return org; } - private void assertOnDemandOrgAssigned(String orgName, PrismObject user) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private void assertOnDemandOrgAssigned(String orgName, PrismObject user) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject org = assertOnDemandOrgExists(orgName); - PrismAsserts.assertPropertyValue(org, OrgType.F_DESCRIPTION, "Created on demand from user "+user.asObjectable().getName()); + PrismAsserts.assertPropertyValue(org, OrgType.F_DESCRIPTION, "Created on demand from user " + user.asObjectable().getName()); assertAssignedOrg(user, org.getOid()); assertHasOrg(user, org.getOid()); } @@ -1125,7 +1121,8 @@ public void test174ModifyUserGuybrushHonorificPrefixNone() throws Exception { then(); assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); assertAssignedNoRole(userAfter); @@ -1191,7 +1188,6 @@ public void test184ModifyUserGuybrushEmployeeTypeNone() throws Exception { assertEquals("Wrong costCenter", "S321", userAfter.asObjectable().getCostCenter()); - assertAssignedNoRole(userAfter); } @@ -1252,8 +1248,6 @@ public void test189ModifyUserGuybrushSubtypeNone() throws Exception { assertAssignedNoRole(userAfter); } - - /** * Assignment mapping with domain. Control: nothing should happen. * MID-3692 @@ -1341,8 +1335,7 @@ public void test192ModifyUserGuybrushOrganizationAddMixed() throws Exception { createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), createPolyString("plutocratic"), - createPolyString("AUTO-didactic") - ); + createPolyString("AUTO-didactic")); // THEN then(); @@ -1358,8 +1351,7 @@ public void test192ModifyUserGuybrushOrganizationAddMixed() throws Exception { createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), createPolyString("plutocratic"), - createPolyString("AUTO-didactic") - ); + createPolyString("AUTO-didactic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); @@ -1387,8 +1379,7 @@ public void test193ModifyUserGuybrushOrganizationAddOutOfDomain() throws Excepti when(); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("meritocratic"), - createPolyString("piratocratic") - ); + createPolyString("piratocratic")); // THEN then(); @@ -1406,8 +1397,7 @@ public void test193ModifyUserGuybrushOrganizationAddOutOfDomain() throws Excepti createPolyString("plutocratic"), createPolyString("AUTO-didactic"), createPolyString("meritocratic"), - createPolyString("piratocratic") - ); + createPolyString("piratocratic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); @@ -1437,23 +1427,22 @@ public void test194ModifyUserGuybrushOrganizationDeleteMixed() throws Exception createPolyString("AUTO-matic"), createPolyString("plutocratic"), createPolyString("meritocratic"), - createPolyString("AUTO-didactic") - ); + createPolyString("AUTO-didactic")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("DEMO-cratic"), createPolyString("AUTO-cratic"), - createPolyString("piratocratic") - ); + createPolyString("piratocratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignments(userAfter, 2); @@ -1479,21 +1468,20 @@ public void test195ModifyUserGuybrushOrganizationDeleteOutOfDomain() throws Exce when(); modifyUserDelete(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("piratocratic"), - createPolyString("DEMO-cratic") - ); + createPolyString("DEMO-cratic")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), - createPolyString("AUTO-cratic") - ); + createPolyString("AUTO-cratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignments(userAfter, 2); @@ -1525,13 +1513,13 @@ public void test196GuybrushAssignCaptain() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), - createPolyString("AUTO-cratic") - ); + createPolyString("AUTO-cratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); @@ -1553,20 +1541,20 @@ public void test197ModifyGuybrushEmployeeTypePirate() throws Exception { // WHEN when(); - modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "PIRATE"); + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "PIRATE"); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), - createPolyString("AUTO-cratic") - ); + createPolyString("AUTO-cratic")); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); assertAssignedRole(userAfter, ROLE_CAPTAIN_OID); @@ -1595,23 +1583,22 @@ public void test198AModifyUserGuybrushOrganizationAddInDomain() throws Exception when(); modifyUserAdd(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("Whateveric"), createPolyString("AUTO-cratic"), createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOCRATIC_OID); @@ -1642,21 +1629,20 @@ public void test198BModifyUserGuybrushOrganizationDeleteMixed() throws Exception when(); modifyUserDelete(USER_GUYBRUSH_OID, UserType.F_ORGANIZATION, task, result, createPolyString("AUTO-cratic"), - createPolyString("Whateveric") - ); + createPolyString("Whateveric")); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); @@ -1683,20 +1669,20 @@ public void test199AGuyBrushModifyEmployeeTypeWannabe() throws Exception { // WHEN when(); - modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "wannabe"); + modifyUserReplace(USER_GUYBRUSH_OID, UserType.F_SUBTYPE, task, result, "wannabe"); // THEN then(); result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); @@ -1729,13 +1715,13 @@ public void test199BGuyBrushUnassignCaptain() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertPropertyValue(userAfter, UserType.F_ORGANIZATION, createPolyString("AUTO-graphic"), - createPolyString("AUTO-matic") - ); + createPolyString("AUTO-matic")); assertAssignedRole(userAfter, ROLE_AUTOMATIC_OID); assertAssignedRole(userAfter, ROLE_AUTOGRAPHIC_OID); @@ -1766,7 +1752,8 @@ public void test199CModifyUserGuybrushOrganizationCleanup() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_GUYBRUSH_OID, null, task, result); display("User after", userAfter); PrismAsserts.assertNoItem(userAfter, UserType.F_ORGANIZATION); @@ -1791,7 +1778,8 @@ public void test200AddUserRapp() throws Exception { modelService.executeChanges(deltas, null, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); PrismAsserts.assertNoItem(userAfter, UserType.F_DESCRIPTION); @@ -1827,7 +1815,8 @@ public void test201AddUserLargo() throws Exception { modelService.executeChanges(deltas, null, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_LARGO_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_LARGO_OID, null, task, result); display("Largo after", userAfter); assertUser(userAfter, USER_LARGO_OID, "largo", "Largo LaGrande", "Largo", "LaGrande"); @@ -1870,7 +1859,8 @@ public void test202AddUserMonkey() throws Exception { modelService.executeChanges(deltas, null, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_THREE_HEADED_MONKEY_OID, null, task, result); + PrismObject userAfter = + modelService.getObject(UserType.class, USER_THREE_HEADED_MONKEY_OID, null, task, result); display("User after", userAfter); // assertUser(userAfter, USER_THREE_HEADED_MONKEY_OID, "monkey", " Monkey", null, "Monkey"); assertUser(userAfter, USER_THREE_HEADED_MONKEY_OID, "monkey", "Three-Headed Monkey", null, "Monkey"); @@ -1987,7 +1977,6 @@ public void test229UnassignRoleSailorFromUserRapp() throws Exception { assertEquals("Wrong costCenter", "G001", userAfterType.getCostCenter()); } - /** * Role Captains has focus mapping for the same costCenter as is given * by the user template. @@ -2034,7 +2023,8 @@ public void test232ModifyUserRappCostCenter() throws Exception { modifyUserReplace(USER_RAPP_OID, UserType.F_COST_CENTER, task, result, "CC-RAPP"); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2067,7 +2057,8 @@ public void test239UnassignRoleCaptainFromUserRapp() throws Exception { unassignRole(USER_RAPP_OID, ROLE_CAPTAIN_OID, task, result); // THEN - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); @@ -2092,20 +2083,23 @@ public void test240ModifyUserRappLocalityScabb() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); assertEquals("Wrong timezone", "High Seas/null", userBefore.asObjectable().getTimezone()); - assertEquals("Wrong locale", null, userBefore.asObjectable().getLocale()); + assertNull("Wrong locale", userBefore.asObjectable().getLocale()); // WHEN - modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("Scabb Island")); + modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, + task, result, PrismTestUtil.createPolyString("Scabb Island")); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2123,7 +2117,6 @@ public void test240ModifyUserRappLocalityScabb() throws Exception { assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); } - /** * Role Rastaman has focus mapping for the same timezone as is given * by the user template. This mapping is normal strength. Even though @@ -2144,7 +2137,8 @@ public void test242AssignRoleRastamanToUserRapp() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2175,17 +2169,20 @@ public void test244ModifyUserRappLocalityCoffin() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); // WHEN - modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, task, result, PrismTestUtil.createPolyString("Coffin")); + modifyUserReplace(USER_RAPP_OID, UserType.F_LOCALITY, + task, result, PrismTestUtil.createPolyString("Coffin")); // THEN result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2213,11 +2210,12 @@ public void test245ModifyUserRappLocalityUnderReconcile() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_RAPP_OID, UserType.F_LOCALITY, - PrismTestUtil.createPolyString("Six feet under")); + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_RAPP_OID, + UserType.F_LOCALITY, PrismTestUtil.createPolyString("Six feet under")); Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); ModelExecuteOptions options = ModelExecuteOptions.createReconcile(); @@ -2228,7 +2226,8 @@ public void test245ModifyUserRappLocalityUnderReconcile() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2258,7 +2257,8 @@ public void test246ModifyUserRappTimezoneMonkey() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); // WHEN @@ -2268,7 +2268,8 @@ public void test246ModifyUserRappTimezoneMonkey() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2298,7 +2299,8 @@ public void test247ModifyUserRappLocaleMI() throws Exception { Task task = getTestTask(); OperationResult result = getTestOperationResult(); - PrismObject userBefore = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userBefore = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User before", userBefore); // WHEN @@ -2308,7 +2310,8 @@ public void test247ModifyUserRappLocaleMI() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); display("User after", userAfter); assertAssignedAccount(userAfter, RESOURCE_DUMMY_BLUE_OID); @@ -2342,7 +2345,8 @@ public void test249UnassignRoleRastamanFromUserRapp() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, USER_RAPP_OID, null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, USER_RAPP_OID, null, task, result); assertUser(userAfter, USER_RAPP_OID, "rapp", "Rapp Scallion", "Rapp", "Scallion"); PrismAsserts.assertNoItem(userAfter, UserType.F_DESCRIPTION); @@ -2354,10 +2358,8 @@ public void test249UnassignRoleRastamanFromUserRapp() throws Exception { assertLinks(userAfter, 1); // Role is unassigned. The mapping was authoritative, so it removed the value - assertEquals("Wrong timezone", null, userAfterType.getTimezone()); - + assertNull("Wrong timezone", userAfterType.getTimezone()); assertEquals("Wrong locale", "MI", userAfterType.getLocale()); - assertEquals("Unexpected value of employeeNumber", "D3ADB33F", userAfterType.getEmployeeNumber()); assertEquals("Wrong costCenter", "CC-RAPP", userAfterType.getCostCenter()); @@ -2459,6 +2461,7 @@ public void test800NullTimeFrom() throws Exception { waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName(USER_JACK_ADDITIONAL_NAME) .extension() @@ -2466,6 +2469,7 @@ public void test800NullTimeFrom() throws Exception { .assertNoItem(PIRACY_LOOT) .end() .assertNoTrigger(); + // @formatter:on } /** @@ -2484,6 +2488,7 @@ public void test802FuneralTimestamp() throws Exception { waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName(USER_JACK_ADDITIONAL_NAME) .extension() @@ -2494,6 +2499,7 @@ public void test802FuneralTimestamp() throws Exception { .single() .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) .assertTimestampFuture(funeralTimestamp, "P1M", 10*1000L); + // @formatter:on } /** @@ -2501,21 +2507,21 @@ public void test802FuneralTimestamp() throws Exception { */ @Test public void test804PreKaboom() throws Exception { - final String TEST_NAME = "test804PreKaboom"; - // GIVEN - clockForward("P2D"); // total override is realTime + 2D + clockForward("P2D"); // total override is realTime + 2D // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName(USER_JACK_ADDITIONAL_NAME) .triggers() .single() .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture("P30D", 5*24*60*60*1000L); + .assertTimestampFuture("P30D", 5 * DAY_MILLIS); + // @formatter:on } /** @@ -2523,15 +2529,14 @@ public void test804PreKaboom() throws Exception { */ @Test public void test808Kaboom() throws Exception { - final String TEST_NAME = "test808Kaboom"; - // GIVEN - clockForward("P1M"); // total override is realTime + 2D + 1M + clockForward("P1M"); // total override is realTime + 2D + 1M // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2542,7 +2547,8 @@ public void test808Kaboom() throws Exception { // Trigger for "tales bomb" mapping (see below) - it was computed as funeralTimestamp + 3M // (i.e. should be approximately equal to clock + 2M - 2D, because clock = realTime + 2D + 1M) .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture("P2M", 5*24*60*60*1000L); + .assertTimestampFuture("P2M", 5 * DAY_MILLIS); + // @formatter:on } /** @@ -2553,15 +2559,14 @@ public void test808Kaboom() throws Exception { */ @Test public void test810PreTalesBomb() throws Exception { - final String TEST_NAME = "test810PreTalesBomb"; - // GIVEN - clockForward("P1D"); // total override is realTime + 2D + 1M + 1D + clockForward("P1D"); // total override is realTime + 2D + 1M + 1D // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2581,7 +2586,8 @@ public void test810PreTalesBomb() throws Exception { // // So setting the tolerance to 7 days should be good enough. .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture("P2M", 7*24*60*60*1000L); + .assertTimestampFuture("P2M", 7 * DAY_MILLIS); + // @formatter:on } /** @@ -2590,8 +2596,6 @@ public void test810PreTalesBomb() throws Exception { */ @Test public void test812TalesBoom() throws Exception { - final String TEST_NAME = "test812TalesBoom"; - // GIVEN clockForward("P3M"); @@ -2599,6 +2603,7 @@ public void test812TalesBoom() throws Exception { waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2606,6 +2611,7 @@ public void test812TalesBoom() throws Exception { .end() .triggers() .assertNone(); + // @formatter:on } /** @@ -2614,14 +2620,13 @@ public void test812TalesBoom() throws Exception { */ @Test public void test813TalesBoomRecompute() throws Exception { - final String TEST_NAME = "test813TalesBoomRecompute"; - // GIVEN // WHEN recomputeUser(USER_JACK_OID); // THEN + // @formatter:off assertUserAfter(USER_JACK_OID) .assertAdditionalName("Kaboom!") .extension() @@ -2641,7 +2646,7 @@ public void test813TalesBoomRecompute() throws Exception { .end() .triggers() .assertNone(); - + // @formatter:on } /** @@ -2658,11 +2663,11 @@ public void test820TalesUnBoom() throws Exception { // The tales mapping is normal. Therefore primary delta will override it. assertUserBefore(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertNoItem(PIRACY_TALES) .end() - .triggers() + .triggers() .assertNone(); // WHEN @@ -2671,11 +2676,11 @@ public void test820TalesUnBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .end() - .triggers() + .triggers() .assertNone(); // WHEN @@ -2683,11 +2688,11 @@ public void test820TalesUnBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .end() - .triggers() + .triggers() .assertNone(); } @@ -2707,16 +2712,15 @@ public void test830PreLootBoom() throws Exception { // The tales mapping is normal. Therefore primary delta will override it. assertUserBefore(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 2*24*60*60*1000L); - + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", 2 * DAY_MILLIS); // WHEN // No delta here. The normal tales mapping will fire again. @@ -2724,30 +2728,30 @@ public void test830PreLootBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 2*24*60*60*1000L); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", 2 * DAY_MILLIS); // WHEN waitForTaskNextRunAssertSuccess(TASK_TRIGGER_SCANNER_OID, true); // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 2*24*60*60*1000L); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", 2 * DAY_MILLIS); } @@ -2758,8 +2762,6 @@ public void test830PreLootBoom() throws Exception { */ @Test public void test832LootBoomConditionFalse() throws Exception { - final String TEST_NAME = "test832LootBoomConditionFalse"; - // GIVEN clockForward("P9M"); @@ -2768,23 +2770,23 @@ public void test832LootBoomConditionFalse() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -2803,23 +2805,23 @@ public void test835LootBoom() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); } @@ -2839,14 +2841,14 @@ public void test840ResetFuneralTimestamp() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() // We have Kaboom. And no funeral timestamp. Tales mapping should be applied. .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // All conditions are satisfied. And no funeral timestamp. Loot mapping should be applied. .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); } @@ -2865,23 +2867,23 @@ public void test843UnLoot() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -2900,23 +2902,23 @@ public void test845ReLoot() throws Exception { // THEN assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); recomputeUser(USER_JACK_OID); assertUserAfter(USER_JACK_OID) - .assertAdditionalName("Kaboom!") - .extension() + .assertAdditionalName("Kaboom!") + .extension() .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() .assertNone(); } @@ -2937,14 +2939,14 @@ public void test850AddCannibalLemonhead() throws Exception { assertSuccess(result); assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -2965,18 +2967,18 @@ public void test852AddCanibalRedSkull() throws Exception { assertSuccess(result); assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from time bomb. There is no condition and the reference time is set. - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1M", 24*60*60*1000L); + // Trigger from time bomb. There is no condition and the reference time is set. + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1M", DAY_MILLIS); } /** @@ -2997,19 +2999,19 @@ public void test854AddCanibalShaprtooth() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Time is not up for tales bomb to explode. .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from tales bomb. We have Kaboomed, the time constraint has activated - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P3M", 24*60*60*1000L); + // Trigger from tales bomb. We have Kaboomed, the time constraint has activated + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P3M", DAY_MILLIS); } /** @@ -3030,15 +3032,15 @@ public void test856AddCanibalOrangeskin() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. .assertNone(); } @@ -3061,15 +3063,15 @@ public void test858AddCanibalCherrybrain() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. But description does not match and condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); @@ -3090,22 +3092,22 @@ public void test859AddCanibalPineapplenose() throws Exception { // WHEN String userOid = addObject( createCannibal(CANNIBAL_PINEAPPLENOSE_USERNAME, "-P1Y1D", false) - .asObjectable().givenName("Lootjack").asPrismObject(), + .asObjectable().givenName("Lootjack").asPrismObject(), task, result); // THEN assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. But description does not match and condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); @@ -3128,14 +3130,14 @@ public void test860AddCannibalRottenLemonhead() throws Exception { assertSuccess(result); assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .assertNone(); } @@ -3155,19 +3157,21 @@ public void test862AddCanibalRottenRedSkull() throws Exception { // THEN assertSuccess(result); + // @formatter:on assertUserAfter(userOid) - .assertNoAdditionalName() - .extension() + .assertNoAdditionalName() + .extension() // Additional name is not Kaboom!, tales are not there .assertNoItem(PIRACY_TALES) // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from time bomb. There is no condition and the reference time is set. - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1M", 1*24*60*60*1000L); + // Trigger from time bomb. There is no condition and the reference time is set. + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1M", DAY_MILLIS); + // @formatter:off } /** @@ -3176,7 +3180,7 @@ public void test862AddCanibalRottenRedSkull() throws Exception { * MID-4630 */ @Test - public void test864AddCanibalRottenShaprtooth() throws Exception { + public void test864AddCannibalRottenSharptooth() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = getTestOperationResult(); @@ -3187,6 +3191,7 @@ public void test864AddCanibalRottenShaprtooth() throws Exception { // THEN assertSuccess(result); + // @formatter:off assertUserAfter(userOid) // Time bomb exploded .assertAdditionalName("Kaboom!") @@ -3203,14 +3208,15 @@ public void test864AddCanibalRottenShaprtooth() throws Exception { .find() // Trigger from tales bomb. We have Kaboomed, the time constraint has activated .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P3M", 1*24*60*60*1000L) + .assertTimestampFuture(funeralTimestamp, "P3M", DAY_MILLIS) .end() .by() .originDescription("loot bomb") .find() // Trigger from loot bomb. We have Kaboomed and we have the right description, the time constraint has activated .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 1*24*60*60*1000L); + .assertTimestampFuture(funeralTimestamp, "P1Y", DAY_MILLIS); + // @formatter:on } /** @@ -3231,19 +3237,19 @@ public void test866AddCanibalRottenOrangeskin() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Description does not match, condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() .single() - // Trigger from loot bomb. We have Kaboomed and we have the right description, the time constraint has activated - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFuture(funeralTimestamp, "P1Y", 1*24*60*60*1000L); + // Trigger from loot bomb. We have Kaboomed and we have the right description, the time constraint has activated + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFuture(funeralTimestamp, "P1Y", DAY_MILLIS); } /** @@ -3265,15 +3271,15 @@ public void test868AddCanibalRottenCherrybrain() throws Exception { assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. But description does not match and condition is false. No loot. .assertNoItem(PIRACY_LOOT) .end() - .triggers() + .triggers() // No trigger for loot bomb. We are already after timeFrom. .assertNone(); } @@ -3292,22 +3298,22 @@ public void test869AddCanibalRottenPineapplenose() throws Exception { // WHEN String userOid = addObject( createCannibal(CANNIBAL_PINEAPPLENOSE_USERNAME, "-P1Y1D", true) - .asObjectable().givenName("Lootjack").asPrismObject(), + .asObjectable().givenName("Lootjack").asPrismObject(), task, result); // THEN assertSuccess(result); assertUserAfter(userOid) - // Time bomb exploded - .assertAdditionalName("Kaboom!") - .extension() + // Time bomb exploded + .assertAdditionalName("Kaboom!") + .extension() // Additional name is Kaboom! and time is up .assertPropertyValuesEqual(PIRACY_TALES, "Once upon a time") // Time is up. Description matches and condition is true. .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) .end() - .triggers() + .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); @@ -3327,12 +3333,13 @@ public void test870AddCanibalRottenPotatoleg() throws Exception { // WHEN String userOid = addObject( createCannibal(CANNIBAL_POTATOLEG_USERNAME, null, true) - .asObjectable().givenName("Lootjack").asPrismObject(), + .asObjectable().givenName("Lootjack").asPrismObject(), task, result); // THEN assertSuccess(result); + // @formatter:off assertUserAfter(userOid) // No funeralTime, no explosion .assertNoAdditionalName() @@ -3340,12 +3347,13 @@ public void test870AddCanibalRottenPotatoleg() throws Exception { // No kaboom, no explosion .assertNoItem(PIRACY_TALES) // No funeral time, description matches and condition is true. - .assertPropertyValuesEqual(PIRACY_LOOT, 1000000) + .assertPropertyValuesEqual(PIRACY_LOOT, 1_000_000) .end() .triggers() // No trigger for loot bomb. Description does not match. // And we are already after timeFrom anyway. .assertNone(); + // @formatter:on } private PrismObject createCannibal(String name, String funeralDateOffset, boolean rotten) throws SchemaException { @@ -3389,7 +3397,7 @@ public void test900DeleteUser() throws Exception { try { PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); display("User after", userJack); - assert false : "User was not deleted: "+userJack; + assert false : "User was not deleted: " + userJack; } catch (ObjectNotFoundException e) { // This is expected } @@ -3454,7 +3462,7 @@ public void test952ModifyJackOrganizationalUnitFD004() throws Exception { assertEquals("Unexpected number of accountRefs", 0, userJackType.getLinkRef().size()); PrismObject org = findObjectByName(OrgType.class, "FD004"); - assertNull("Found org "+org+" but not expecting it", org); + assertNull("Found org " + org + " but not expecting it", org); } /** @@ -3476,10 +3484,10 @@ public void test960ReconcileUserJackWithTemplate() throws Exception { // THEN result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); - display("User after", userJack); + PrismObject userJack = modelService.getObject(UserType.class, USER_JACK_OID, null, task, result); + display("User after", userJack); - PrismAsserts.assertPropertyValue(userJack, UserType.F_DESCRIPTION, "Where's the rum?"); + PrismAsserts.assertPropertyValue(userJack, UserType.F_DESCRIPTION, "Where's the rum?"); assertAssignedAccount(userJack, RESOURCE_DUMMY_BLUE_OID); assertOnDemandOrgAssigned("FD004", userJack); @@ -3529,7 +3537,7 @@ public void test980DeleteUserGivenName() throws Exception { .givenName("jim") .subtype(SUBTYPE_MID_5892) .beginAssignment() - .targetRef(SystemObjectsType.ROLE_SUPERUSER.value(), RoleType.COMPLEX_TYPE) + .targetRef(SystemObjectsType.ROLE_SUPERUSER.value(), RoleType.COMPLEX_TYPE) .end(); repositoryService.addObject(user.asPrismObject(), null, result); @@ -3544,10 +3552,11 @@ public void test980DeleteUserGivenName() throws Exception { then(); assertSuccess(result); - PrismObject userAfter = modelService.getObject(UserType.class, user.getOid(), null, task, result); + PrismObject userAfter = modelService.getObject( + UserType.class, user.getOid(), null, task, result); display("User after", userAfter); - AssignmentType assignment = assertAssignedRole(userAfter, SystemObjectsType.ROLE_SUPERUSER.value()); + assertAssignedRole(userAfter, SystemObjectsType.ROLE_SUPERUSER.value()); } // @Override diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java index 012a91338dc..4a9da91f041 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java @@ -6,6 +6,15 @@ */ package com.evolveum.midpoint.model.intest; +import java.io.File; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.polystring.PolyString; @@ -15,24 +24,15 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; -import java.io.File; +import com.evolveum.midpoint.util.exception.CommonException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * User template with "mapping range" features. - * - * @author mederly - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUserTemplateWithRanges extends AbstractInitializedModelIntegrationTest { @@ -197,8 +197,6 @@ public void test140ChangeManagerAndRecomputeElaineAgain() throws Exception { */ @Test public void test200SimpleOrgUnitAddition() throws Exception { - final String TEST_NAME = "test200SimpleOrgUnitAddition"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -206,8 +204,8 @@ public void test200SimpleOrgUnitAddition() throws Exception { // WHEN executeChanges( deltaFor(UserType.class) - .item(UserType.F_ORGANIZATIONAL_UNIT).add( - PolyString.fromOrig("U1"), + .item(UserType.F_ORGANIZATIONAL_UNIT) + .add(PolyString.fromOrig("U1"), PolyString.fromOrig("U2"), PolyString.fromOrig("U3"), PolyString.fromOrig("U4")) @@ -239,8 +237,6 @@ public void test200SimpleOrgUnitAddition() throws Exception { */ @Test public void test210RemoveUnit1() throws Exception { - final String TEST_NAME = "test210RemoveUnit1"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -278,8 +274,6 @@ public void test210RemoveUnit1() throws Exception { */ @Test public void test220RemoveUnit2AndNumber() throws Exception { - final String TEST_NAME = "test220RemoveUnit2AndNumber"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -317,8 +311,6 @@ public void test220RemoveUnit2AndNumber() throws Exception { */ @Test public void test230RestoreNumber() throws Exception { - final String TEST_NAME = "test230RestoreNumber"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -352,8 +344,6 @@ public void test230RestoreNumber() throws Exception { @Test public void test300GuybrushBloodyNose() throws Exception { - final String TEST_NAME = "test300GuybrushBloodyNose"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -370,6 +360,7 @@ public void test300GuybrushBloodyNose() throws Exception { then(); assertSuccess(result); + // @formatter:off assertUserAfter(USER_GUYBRUSH_OID) .assertTitle(ROLE_BLOODY_NOSE_NAME) .assignments() @@ -378,13 +369,11 @@ public void test300GuybrushBloodyNose() throws Exception { .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) .activation() .assertNoValidTo(); - + // @formatter:on } @Test public void test309GuybrushNotBloody() throws Exception { - final String TEST_NAME = "test309GuybrushNotBloody"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -402,16 +391,12 @@ public void test309GuybrushNotBloody() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertNoTitle() - .assignments() - .assertNone(); - + .assertNoTitle() + .assignments().assertNone(); } @Test public void test310GuybrushBloodyNoseFuneral() throws Exception { - final String TEST_NAME = "test310GuybrushBloodyNoseFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -432,20 +417,18 @@ public void test310GuybrushBloodyNoseFuneral() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertTitle(ROLE_BLOODY_NOSE_NAME) - .assignments() + .assertTitle(ROLE_BLOODY_NOSE_NAME) + .assignments() .single() - .assertTargetOid(ROLE_BLOODY_NOSE_OID) - .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) - .activation() - .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); + .assertTargetOid(ROLE_BLOODY_NOSE_OID) + .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) + .activation() + .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); } @Test public void test319GuybrushNoBloodyNoseFuneral() throws Exception { - final String TEST_NAME = "test319GuybrushNoBloodyNoseFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -463,16 +446,14 @@ public void test319GuybrushNoBloodyNoseFuneral() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertNoTitle() - .assignments() + .assertNoTitle() + .assignments() .assertNone(); } @Test public void test320GuybrushBloodyNose() throws Exception { - final String TEST_NAME = "test320GuybrushBloodyNose"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -493,20 +474,18 @@ public void test320GuybrushBloodyNose() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertTitle(ROLE_BLOODY_NOSE_NAME) - .assignments() + .assertTitle(ROLE_BLOODY_NOSE_NAME) + .assignments() .single() - .assertTargetOid(ROLE_BLOODY_NOSE_OID) - .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) - .activation() - .assertNoValidTo(); + .assertTargetOid(ROLE_BLOODY_NOSE_OID) + .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) + .activation() + .assertNoValidTo(); } @Test public void test322GuybrushSetFuneral() throws Exception { - final String TEST_NAME = "test322GuybrushSetFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -521,20 +500,18 @@ public void test322GuybrushSetFuneral() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertTitle(ROLE_BLOODY_NOSE_NAME) - .assignments() + .assertTitle(ROLE_BLOODY_NOSE_NAME) + .assignments() .single() - .assertTargetOid(ROLE_BLOODY_NOSE_OID) - .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) - .activation() - .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); + .assertTargetOid(ROLE_BLOODY_NOSE_OID) + .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) + .activation() + .assertValidTo(GUYBRUSH_FUNERAL_DATE_123456_CAL); } @Test public void test324GuybrushSetFuneral22222() throws Exception { - final String TEST_NAME = "test324GuybrushSetFuneral22222"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -548,6 +525,7 @@ public void test324GuybrushSetFuneral22222() throws Exception { then(); assertSuccess(result); + // @formatter:off assertUserAfter(USER_GUYBRUSH_OID) .assertTitle(ROLE_BLOODY_NOSE_NAME) .assignments() @@ -556,6 +534,7 @@ public void test324GuybrushSetFuneral22222() throws Exception { .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) .activation() .assertValidTo(GUYBRUSH_FUNERAL_DATE_22222_CAL); + // @formatter:on } /** @@ -563,8 +542,6 @@ public void test324GuybrushSetFuneral22222() throws Exception { */ @Test public void test326GuybrushNoFuneral() throws Exception { - final String TEST_NAME = "test326GuybrushNoFuneral"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -578,6 +555,7 @@ public void test326GuybrushNoFuneral() throws Exception { then(); assertSuccess(result); + // @formatter:off assertUserAfter(USER_GUYBRUSH_OID) .assertTitle(ROLE_BLOODY_NOSE_NAME) .assignments() @@ -586,12 +564,11 @@ public void test326GuybrushNoFuneral() throws Exception { .assertSubtype(BLOODY_ASSIGNMENT_SUBTYPE) .activation() .assertNoValidTo(); + // @formatter:on } @Test public void test329GuybrushNoBloodyNose() throws Exception { - final String TEST_NAME = "test329GuybrushNoBloodyNose"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -609,10 +586,8 @@ public void test329GuybrushNoBloodyNose() throws Exception { assertSuccess(result); assertUserAfter(USER_GUYBRUSH_OID) - .assertNoTitle() - .assignments() - .assertNone(); - + .assertNoTitle() + .assignments().assertNone(); } private void changeManagerRaw(String id, Task task, OperationResult result) throws CommonException { @@ -630,5 +605,4 @@ private void changeEmployeeIdRaw(String id, Task initTask, OperationResult initR .asObjectDelta(USER_ELAINE_OID), ModelExecuteOptions.createRaw(), initTask, initResult); } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java index efc65c67e37..fb4b2738b3e 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyConsistency.java @@ -105,7 +105,6 @@ public void test000Integrity() throws Exception { */ @Test public void test050AddAccountWill() throws Exception { - final String TEST_NAME = "test050AddAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -164,7 +163,6 @@ public void test050AddAccountWill() throws Exception { @Test public void test100AddAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test100AddAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -229,7 +227,6 @@ public void test102GetAccountMorganRecovery() throws Exception { */ @Test public void test104RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test104RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -260,7 +257,6 @@ public void test104RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test105GetForceRefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test105GetForceRefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -299,7 +295,6 @@ public void test105GetForceRefreshAccountMorganCommunicationFailure() throws Exc */ @Test public void test106RefreshAccountMorganCommunicationFailureRetry() throws Exception { - final String TEST_NAME = "test106RefreshAccountMorganCommunicationFailureRetry"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -338,7 +333,6 @@ public void test106RefreshAccountMorganCommunicationFailureRetry() throws Except */ @Test public void test108RefreshAccountMorganCommunicationFailureRetryAgain() throws Exception { - final String TEST_NAME = "test108RefreshAccountMorganCommunicationFailureRetryAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -465,7 +459,6 @@ private void assertMorganDead() throws Exception { */ @Test public void test109RefreshAccountMorganDead() throws Exception { - final String TEST_NAME = "test109RefreshAccountMorganDead"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -496,7 +489,6 @@ public void test109RefreshAccountMorganDead() throws Exception { */ @Test public void test110AddAccountMorganAgainCommunicationFailure() throws Exception { - final String TEST_NAME = "test110AddAccountMorganAgainCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -536,7 +528,6 @@ public void test110AddAccountMorganAgainCommunicationFailure() throws Exception */ @Test public void test114RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test114RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -569,7 +560,6 @@ public void test114RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test116RefreshAccountMorganRetrySuccess() throws Exception { - final String TEST_NAME = "test116RefreshAccountMorganRetrySuccess"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -604,8 +594,6 @@ public void test116RefreshAccountMorganRetrySuccess() throws Exception { @Test public void test120ModifyMorganFullNameCommunicationFailure() throws Exception { - final String TEST_NAME = "test120ModifyMorganFullNameCommunicationFailure"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -641,7 +629,6 @@ public void test120ModifyMorganFullNameCommunicationFailure() throws Exception { */ @Test public void test124RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test124RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -672,7 +659,6 @@ public void test124RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test126RefreshAccountMorganCommunicationFailureRetry() throws Exception { - final String TEST_NAME = "test126RefreshAccountMorganCommunicationFailureRetry"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -711,7 +697,6 @@ public void test126RefreshAccountMorganCommunicationFailureRetry() throws Except */ @Test public void test128RefreshAccountMorganCommunicationFailureRetryAgain() throws Exception { - final String TEST_NAME = "test128RefreshAccountMorganCommunicationFailureRetryAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -747,7 +732,6 @@ public void test128RefreshAccountMorganCommunicationFailureRetryAgain() throws E */ @Test public void test129RefreshAccountMorganFailed() throws Exception { - final String TEST_NAME = "test129RefreshAccountMorganFailed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -775,8 +759,6 @@ public void test129RefreshAccountMorganFailed() throws Exception { @Test public void test130ModifyMorganFullNameAgainCommunicationFailure() throws Exception { - final String TEST_NAME = "test130ModifyMorganFullNameAgainCommunicationFailure"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -813,7 +795,6 @@ public void test130ModifyMorganFullNameAgainCommunicationFailure() throws Except */ @Test public void test132GetAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test132GetAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -848,7 +829,6 @@ public void test132GetAccountMorganCommunicationFailure() throws Exception { */ @Test(enabled = false) // MID-4796 public void test133GetAccountMorganStalenessZeroCommunicationFailure() throws Exception { - final String TEST_NAME = "test133GetAccountMorganStalenessZeroCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -888,7 +868,6 @@ public void test133GetAccountMorganStalenessZeroCommunicationFailure() throws Ex */ @Test public void test134GetAccountMorganForceRefreshRetryCommunicationFailure() throws Exception { - final String TEST_NAME = "test134GetAccountMorganForceRefreshRetryCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -922,7 +901,6 @@ public void test134GetAccountMorganForceRefreshRetryCommunicationFailure() throw */ @Test public void test136RefreshAccountMorganRetrySuccess() throws Exception { - final String TEST_NAME = "test136RefreshAccountMorganRetrySuccess"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -957,8 +935,6 @@ public void test136RefreshAccountMorganRetrySuccess() throws Exception { @Test public void test170DeleteMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test170DeleteMorganCommunicationFailure"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -993,7 +969,6 @@ public void test170DeleteMorganCommunicationFailure() throws Exception { */ @Test public void test174RefreshAccountMorganCommunicationFailure() throws Exception { - final String TEST_NAME = "test174RefreshAccountMorganCommunicationFailure"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1024,7 +999,6 @@ public void test174RefreshAccountMorganCommunicationFailure() throws Exception { */ @Test public void test176RefreshAccountMorganCommunicationFailureRetry() throws Exception { - final String TEST_NAME = "test176RefreshAccountMorganCommunicationFailureRetry"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1063,7 +1037,6 @@ public void test176RefreshAccountMorganCommunicationFailureRetry() throws Except */ @Test public void test178RefreshAccountMorganCommunicationFailureRetryAgain() throws Exception { - final String TEST_NAME = "test178RefreshAccountMorganCommunicationFailureRetryAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1098,7 +1071,6 @@ public void test178RefreshAccountMorganCommunicationFailureRetryAgain() throws E */ @Test public void test179RefreshAccountMorganFailed() throws Exception { - final String TEST_NAME = "test179RefreshAccountMorganFailed"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1126,8 +1098,6 @@ public void test179RefreshAccountMorganFailed() throws Exception { @Test public void test180DeleteMorganCommunicationFailureAgain() throws Exception { - final String TEST_NAME = "test180DeleteMorganCommunicationFailureAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1163,7 +1133,6 @@ public void test180DeleteMorganCommunicationFailureAgain() throws Exception { */ @Test public void test186RefreshAccountMorganRetrySuccess() throws Exception { - final String TEST_NAME = "test186RefreshAccountMorganRetrySuccess"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1205,7 +1174,6 @@ public void test186RefreshAccountMorganRetrySuccess() throws Exception { */ @Test public void test190AccountMorganDeadExpireOperation() throws Exception { - final String TEST_NAME = "test190AccountMorganDeadExpireOperation"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1290,7 +1258,6 @@ public void test190AccountMorganDeadExpireOperation() throws Exception { */ @Test public void test192AccountMorganSecondDeadExpireOperation() throws Exception { - final String TEST_NAME = "test192AccountMorganSecondDeadExpireOperation"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1359,7 +1326,6 @@ public void test192AccountMorganSecondDeadExpireOperation() throws Exception { */ @Test public void test194AccountMorganDeadExpireShadow() throws Exception { - final String TEST_NAME = "test194AccountMorganDeadExpireShadow"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1395,7 +1361,6 @@ public void test194AccountMorganDeadExpireShadow() throws Exception { */ @Test public void test196AccountMorganSecondDeadExpireShadow() throws Exception { - final String TEST_NAME = "test196AccountMorganSecondDeadExpireShadow"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1432,7 +1397,6 @@ public void test196AccountMorganSecondDeadExpireShadow() throws Exception { */ @Test public void test800AddAccountMorganAlreadyExists() throws Exception { - final String TEST_NAME = "test800AddAccountMorganAlreadyExists"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1513,7 +1477,6 @@ public void test800AddAccountMorganAlreadyExists() throws Exception { */ @Test public void test802AddAccountMorganAlreadyExistsAgain() throws Exception { - final String TEST_NAME = "test802AddAccountMorganAlreadyExistsAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1599,7 +1562,6 @@ public void test802AddAccountMorganAlreadyExistsAgain() throws Exception { @Test public void test804AddAccountElizabeth() throws Exception { - final String TEST_NAME = "test804AddAccountElizabeth"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1632,7 +1594,6 @@ public void test804AddAccountElizabeth() throws Exception { */ @Test public void test806RenameAccountElizabethAlreadyExists() throws Exception { - final String TEST_NAME = "test806RenameAccountElizabethAlreadyExists"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1713,7 +1674,6 @@ public void test806RenameAccountElizabethAlreadyExists() throws Exception { */ @Test public void test808RenameAccountElizabethAlreadyExistsAgain() throws Exception { - final String TEST_NAME = "test808RenameAccountElizabethAlreadyExistsAgain"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1807,7 +1767,6 @@ public void test808RenameAccountElizabethAlreadyExistsAgain() throws Exception { */ @Test public void test810GetAccountMorganNotFound() throws Exception { - final String TEST_NAME = "test810GetAccountMorganNotFound"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1875,7 +1834,6 @@ public void test810GetAccountMorganNotFound() throws Exception { */ @Test public void test812ModifyAccountWillNotFound() throws Exception { - final String TEST_NAME = "test812ModifyAccountWillNotFound"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1949,7 +1907,6 @@ public void test812ModifyAccountWillNotFound() throws Exception { */ @Test public void test814DeleteAccountElizabethNotFound() throws Exception { - final String TEST_NAME = "test814DeleteAccountElizabethNotFound"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2014,7 +1971,6 @@ public void test814DeleteAccountElizabethNotFound() throws Exception { */ @Test public void test816AddAccountElizabethAfterDeathAlreadyExists() throws Exception { - final String TEST_NAME = "test816AddAccountElizabethAfterDeathAlreadyExists"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2083,7 +2039,6 @@ public void test816AddAccountElizabethAfterDeathAlreadyExists() throws Exception */ @Test public void test900GetAccountMurrayPending() throws Exception { - final String TEST_NAME = "test900GetAccountMurrayPending"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2694,7 +2649,7 @@ private void assertMorganDeleteFailed() throws Exception { assertNotNull("Shadow was not created in the repository", repoShadow); // @formatter:off - ShadowAsserter shadowAsserter = ShadowAsserter.forShadow(repoShadow, "repository"); + ShadowAsserter shadowAsserter = ShadowAsserter.forShadow(repoShadow, "repository"); shadowAsserter .display() .pendingOperations() @@ -2793,7 +2748,7 @@ private void assertMorganDeleteFailed() throws Exception { .assertPassword(ACCOUNT_MORGAN_PASSWORD); } - private void assertDeletedMorgan(int expectedAttemptNumber, int expectenNumberOfPendingOperations) throws Exception { + private void assertDeletedMorgan(int expectedAttemptNumber, int expectedNumberOfPendingOperations) throws Exception { PrismObject repoShadow = getShadowRepo(shadowMorganOid); assertNotNull("Shadow was not created in the repository", repoShadow); @@ -2803,7 +2758,7 @@ private void assertDeletedMorgan(int expectedAttemptNumber, int expectenNumberOf shadowAsserter .display() .pendingOperations() - .assertOperations(expectenNumberOfPendingOperations) + .assertOperations(expectedNumberOfPendingOperations) .by() .executionStatus(PendingOperationExecutionStatusType.COMPLETED) .resultStatus(OperationResultStatusType.SUCCESS) @@ -2837,7 +2792,7 @@ private void assertDeletedMorgan(int expectedAttemptNumber, int expectenNumberOf .assertSize(2) .end() .pendingOperations() - .assertOperations(expectenNumberOfPendingOperations) + .assertOperations(expectedNumberOfPendingOperations) .by() .executionStatus(PendingOperationExecutionStatusType.COMPLETED) .resultStatus(OperationResultStatusType.SUCCESS) diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index 7222cc172ae..e7bcc01508a 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -1825,7 +1825,7 @@ protected void displaySkip() { */ @SuppressWarnings("unused") protected void displayHEREHERE() { - IntegrationTestTools.display("HEREHERE"); + display(contextName() + "HEREHERE"); } public static void display(String message, SearchResultEntry response) { From 694fb71d764a61e4e95304f9bd1dd3b0f4965d74 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 12:39:03 +0100 Subject: [PATCH 13/55] POM: added mvn example to run single IT test from "extratest" module --- pom.xml | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/pom.xml b/pom.xml index 5cf468d864b..4e0e126edb3 100644 --- a/pom.xml +++ b/pom.xml @@ -41,10 +41,15 @@ Extra test run with custom JVM args (we have 16g on CI server, but it works without args too), runs just under 900 tests, skips distribution and any common unit/IT tests (~1h50m): mvn clean install -P extratest,-dist -Dsurefire.args="-Xmx8g" -Dfailsafe.args="-Xmx8g -Duser.language=en" + (Skipping of default tests is managed by "extratest" profile.) Extra test run for a single module, -D property matches the module in -pl: mvn clean install -DskipConnTests=false -pl testing/conntest + Running a single IT test class in one module from the "extra" set with output to stdout: + mvn integration-test -DskipConnTests=false -DredirectTestOutputToFile=false -pl testing/conntest -Dit.test=TestAdLdapChimera + Note usage of "it.test" property (for failsafe), not just "test" (for surefire). + Full build with extra tests for a single module, "-DskipTests" suppresses other default tests: mvn clean install -P -dist -DskipTests -DskipStoryTests=false See "extratest" profile in testing/pom.xml for all individual properties enabling extra tests. From 449345c4ce9777718c34f2bec98f3f867385da86 Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Fri, 6 Mar 2020 14:52:31 +0100 Subject: [PATCH 14/55] Add test for MID-6045 (not failing) --- .../midpoint/prism/xml/XmlTypeConverter.java | 4 ++ .../functions/BasicExpressionFunctions.java | 3 +- .../model/intest/TestUserTemplate.java | 47 ++++++++++++++++--- .../user-template-mid-6045.xml | 47 +++++++++++++++++++ 4 files changed, 93 insertions(+), 8 deletions(-) create mode 100644 model/model-intest/src/test/resources/object-template/user-template-mid-6045.xml diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java index 22a30976ca6..4bcfc6cd21c 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/xml/XmlTypeConverter.java @@ -185,6 +185,10 @@ public static Date toDate(XMLGregorianCalendar xmlCal) { return xmlCal != null ? new Date(xmlCal.toGregorianCalendar().getTimeInMillis()) : null; } + public static XMLGregorianCalendar fromNow(String timeSpec) { + return fromNow(XmlTypeConverter.createDuration(timeSpec)); + } + public static XMLGregorianCalendar fromNow(Duration duration) { XMLGregorianCalendar rv = createXMLGregorianCalendar(System.currentTimeMillis()); rv.add(duration); diff --git a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java index a864fc82317..3dfeb599ad8 100644 --- a/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java +++ b/model/model-common/src/main/java/com/evolveum/midpoint/model/common/expression/functions/BasicExpressionFunctions.java @@ -790,10 +790,9 @@ public XMLGregorianCalendar currentDateTime() { } public XMLGregorianCalendar fromNow(String timeSpec) { - return XmlTypeConverter.fromNow(XmlTypeConverter.createDuration(timeSpec)); + return XmlTypeConverter.fromNow(timeSpec); } - public XMLGregorianCalendar addDuration(XMLGregorianCalendar now, Duration duration) { if (now == null) { return null; diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java index fcdffed8f4c..a3a5180a123 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java @@ -78,6 +78,7 @@ public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { protected static final String USER_TEMPLATE_USELESS_OID = "29b2936a-d1f6-4942-8e44-9ba44fc27423"; protected static final TestResource USER_TEMPLATE_MID_5892 = new TestResource(TEST_DIR, "user-template-mid-5892.xml", "064993c0-34b4-4440-9331-e909fc923504"); + private static final TestResource USER_TEMPLATE_MID_6045 = new TestResource(TEST_DIR, "user-template-mid-6045.xml", "f3dbd582-11dc-473f-8b51-a30be5cbd5ce"); private static final String ACCOUNT_STAN_USERNAME = "stan"; private static final String ACCOUNT_STAN_FULLNAME = "Stan the Salesman"; @@ -85,6 +86,7 @@ public class TestUserTemplate extends AbstractInitializedModelIntegrationTest { private static final String SUBTYPE_MAROONED = "marooned"; private static final String SUBTYPE_USELESS = "useless"; private static final String SUBTYPE_MID_5892 = "mid-5892"; + private static final String SUBTYPE_MID_6045 = "mid-6045"; private static final int NUMBER_OF_IMPORTED_ROLES = 5; @@ -114,11 +116,13 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti repoAddObjectFromFile(USER_TEMPLATE_MAROONED_FILE, initResult); repoAddObjectFromFile(USER_TEMPLATE_USELESS_FILE, initResult); repoAdd(USER_TEMPLATE_MID_5892, initResult); + repoAdd(USER_TEMPLATE_MID_6045, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, USER_TEMPLATE_COMPLEX_OID, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_MAROONED, USER_TEMPLATE_MAROONED_OID, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_USELESS, USER_TEMPLATE_USELESS_OID, initResult); setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_MID_5892, USER_TEMPLATE_MID_5892.oid, initResult); + setDefaultObjectTemplate(UserType.COMPLEX_TYPE, SUBTYPE_MID_6045, USER_TEMPLATE_MID_6045.oid, initResult); } protected int getNumberOfRoles() { @@ -3547,12 +3551,43 @@ public void test980DeleteUserGivenName() throws Exception { PrismObject userAfter = modelService.getObject(UserType.class, user.getOid(), null, task, result); display("User after", userAfter); - AssignmentType assignment = assertAssignedRole(userAfter, SystemObjectsType.ROLE_SUPERUSER.value()); + assertAssignedRole(userAfter, SystemObjectsType.ROLE_SUPERUSER.value()); } -// @Override -// protected TracingProfileType getTestMethodTracingProfile() { -// return createModelLoggingTracingProfile() -// .fileNamePattern(TEST_METHOD_TRACING_FILENAME_PATTERN); -// } + /** + * MID-6045 + */ + @Test + public void test990SpecialTimedMapping() throws Exception { + Task task = getTestTask(); + OperationResult result = task.getResult(); + + XMLGregorianCalendar firstTriggerTime = XmlTypeConverter.fromNow("PT1M"); + + UserType user = new UserType(prismContext) + .name("test990SpecialTimedMapping") + .givenName("jim") + .subtype(SUBTYPE_MID_6045) + .beginTrigger() + .timestamp(firstTriggerTime) + .handlerUri(RecomputeTriggerHandler.HANDLER_URI) + .end() + .beginAssignment() + .targetRef(SystemObjectsType.ROLE_SUPERUSER.value(), RoleType.COMPLEX_TYPE) + .end(); + repositoryService.addObject(user.asPrismObject(), null, result); + + when(); + recomputeUser(user.getOid(), task, result); + + then(); + assertSuccess(result); + + assertUser(user.getOid(), "user after") + .display() + .triggers() + .assertTriggers(3) // for some reason two new triggers are created + .end() + .assertAssignments(1); + } } diff --git a/model/model-intest/src/test/resources/object-template/user-template-mid-6045.xml b/model/model-intest/src/test/resources/object-template/user-template-mid-6045.xml new file mode 100644 index 00000000000..3ddb2fd3ffd --- /dev/null +++ b/model/model-intest/src/test/resources/object-template/user-template-mid-6045.xml @@ -0,0 +1,47 @@ + + + + User Template 6045 + + + strong + + name + + + + + + assignment + + + + + + + + + + + + + From 4bc7f532618d6e87ff52af10d75022122dec14a3 Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Fri, 6 Mar 2020 16:55:34 +0100 Subject: [PATCH 15/55] task preview page --- .../gui/api/util/WebModelServiceUtils.java | 1692 ++++++------- .../component/assignment/AssignmentPanel.java | 2 +- .../web/page/admin/PageAdminFocus.java | 1983 ++++++++-------- .../page/admin/PageAdminObjectDetails.java | 2101 +++++++++-------- .../web/page/admin/server/PageTask.java | 10 +- 5 files changed, 2891 insertions(+), 2897 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java index ff721c90bbc..72f8f7e0879 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebModelServiceUtils.java @@ -1,844 +1,848 @@ -/* - * 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.gui.api.util; - -import static com.evolveum.midpoint.schema.GetOperationOptions.createNoFetchCollection; - -import java.util.*; - -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.LocaleUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.Session; -import org.apache.wicket.ThreadContext; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; - -import com.evolveum.midpoint.common.LocalizationService; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.ModelInteractionService; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; -import com.evolveum.midpoint.prism.delta.ChangeType; -import com.evolveum.midpoint.prism.delta.DeltaFactory; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.GetOperationOptionsBuilder; -import com.evolveum.midpoint.schema.SchemaHelper; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.security.api.MidPointPrincipal; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; -import com.evolveum.midpoint.util.exception.AuthorizationException; -import com.evolveum.midpoint.util.exception.CommonException; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.page.login.PageLogin; -import com.evolveum.midpoint.web.security.MidPointApplication; -import com.evolveum.midpoint.web.security.util.SecurityUtils; -import com.evolveum.prism.xml.ns._public.types_3.EvaluationTimeType; - -import javax.xml.namespace.QName; - -/** - * Utility class that contains methods that interact with ModelService and other - * midPoint components. - * - * @author lazyman - */ -public class WebModelServiceUtils { - - private static final Trace LOGGER = TraceManager.getTrace(WebModelServiceUtils.class); - - private static final String DOT_CLASS = WebModelServiceUtils.class.getName() + "."; - private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; - private static final String OPERATION_DELETE_OBJECT = DOT_CLASS + "deleteObject"; - private static final String OPERATION_SEARCH_OBJECTS = DOT_CLASS + "searchObjects"; - private static final String OPERATION_SAVE_OBJECT = DOT_CLASS + "saveObject"; - private static final String OPERATION_LOAD_OBJECT_REFS = DOT_CLASS + "loadObjectReferences"; - private static final String OPERATION_COUNT_OBJECT = DOT_CLASS + "countObjects"; - private static final String OPERATION_ASSUME_POWER_OF_ATTORNEY = DOT_CLASS + "assumePowerOfAttorney"; - private static final String OPERATION_DROP_POWER_OF_ATTORNEY = DOT_CLASS + "dropPowerOfAttorney"; - private static final String OPERATION_GET_SYSTEM_CONFIG = DOT_CLASS + "getSystemConfiguration"; - private static final String OPERATION_LOAD_FLOW_POLICY = DOT_CLASS + "loadFlowPolicy"; - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page) { - return resolveReferenceName(ref, page, false); - } - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, boolean translate) { - Task task = page.createSimpleTask(WebModelServiceUtils.class.getName() + ".resolveReferenceName"); - return resolveReferenceName(ref, page, task, task.getResult(), translate); - } - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result) { - return resolveReferenceName(ref, page, task, result, false); - } - - public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result, boolean translate) { - if (ref == null) { - return null; - } - if (ref.getTargetName() != null) { - return translate ? page.getLocalizationService().translate(ref.getTargetName().toPolyString(), page.getLocale(), true) - : ref.getTargetName().getOrig(); - } - if (StringUtils.isEmpty(ref.getOid()) || ref.getType() == null){ - return null; - } - PrismObject object = resolveReferenceNoFetch(ref, page, task, result); - if (object == null) { - return ref.getOid(); - } else { - ref.asReferenceValue().setObject(object); - return WebComponentUtil.getName(object, translate); - } - } - - public static PrismObject resolveReferenceNoFetch(ObjectReferenceType reference, PageBase page, Task task, OperationResult result) { - if (reference == null) { - return null; - } - if (reference.asReferenceValue().getObject() != null) { - return reference.asReferenceValue().getObject(); - } - PrismContext prismContext = page.getPrismContext(); - if (reference.getType() == null) { - LOGGER.error("No type in {}", reference); - return null; - } - PrismObjectDefinition definition = prismContext.getSchemaRegistry().findObjectDefinitionByType(reference.getType()); - if (definition == null) { - LOGGER.error("No definition for {} was found", reference.getType()); - return null; - } - if (reference.getOid() == null) { - if (reference.getResolutionTime() == EvaluationTimeType.RUN) { - // Runtime reference resolution. Ignore it for now. Later we maybe would want to resolve it here. - // But it may resolve to several objects .... - return null; - } else { - LOGGER.error("Null OID in reference {}", reference); - // Throw an exception instead? Maybe not. We want GUI to be robust. - return null; - } - } - return loadObject(definition.getCompileTimeClass(), reference.getOid(), createNoFetchCollection(), page, task, result); - } - - public static List createObjectReferenceList(Class type, PageBase page, Map referenceMap){ - referenceMap.clear(); - - OperationResult result = new OperationResult(OPERATION_LOAD_OBJECT_REFS); -// Task task = page.createSimpleTask(OPERATION_LOAD_PASSWORD_POLICIES); - - try { - List> objects = searchObjects(type, null, result, page); - result.recomputeStatus(); - List references = new ArrayList<>(); - - for(PrismObject object: objects){ - referenceMap.put(object.getOid(), WebComponentUtil.getName(object)); - references.add(ObjectTypeUtil.createObjectRef(object, page.getPrismContext())); - - } - return references; - } catch (Exception e){ - result.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadPasswordPolicies").getString(), e); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load password policies", e); - } - - // TODO - show error somehow - // if(!result.isSuccess()){ - // getPageBase().showResult(result); - // } - - return null; - } - - public static String runTask(TaskType taskToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ - try { - ObjectDelta delta = DeltaFactory.Object.createAddDelta(taskToRun.asPrismObject()); - pageBase.getPrismContext().adopt(delta); - pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, - operationalTask, parentResult); - parentResult.recordInProgress(); - parentResult.setBackgroundTaskOid(delta.getOid()); - pageBase.showResult(parentResult); - return delta.getOid(); - } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException - | ExpressionEvaluationException | CommunicationException | ConfigurationException - | PolicyViolationException | SecurityViolationException e) { - // TODO Auto-generated catch block -// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); - parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); - return null; - } - - } - - public static void runTask(Collection tasksToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ -// try { - - for (TaskType taskToRun : tasksToRun){ - runTask(tasksToRun, operationalTask, parentResult, pageBase); - } - -// } -// ObjectDelta delta = ObjectDelta.createAddDelta(taskToRun.asPrismObject()); -// pageBase.getPrismContext().adopt(delta); -// pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, -// operationalTask, parentResult); -// parentResult.recordInProgress(); -// parentResult.setBackgroundTaskOid(delta.getOid()); -// pageBase.showResult(parentResult); -// return delta.getOid(); -// } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException -// | ExpressionEvaluationException | CommunicationException | ConfigurationException -// | PolicyViolationException | SecurityViolationException e) { -// // TODO Auto-generated catch block -//// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); -// parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); -// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); -// return null; -// } - - } - - public static PrismObject loadObject(PrismReferenceValue objectRef, QName expectedTargetType, PageBase pageBase, Task task, OperationResult result) { - if (objectRef == null) { - return null; - } - - if (QNameUtil.match(expectedTargetType, objectRef.getTargetType())) { - Class type = pageBase.getPrismContext().getSchemaRegistry().determineClassForType(objectRef.getTargetType()); - PrismObject resourceType = WebModelServiceUtils.loadObject(type, objectRef.getOid(), GetOperationOptions.createNoFetchCollection(), pageBase, task, result); - return resourceType; - } - - return null; - } - - @Nullable - public static PrismObject loadObject(ObjectReferenceType objectReference, - PageBase page, Task task, OperationResult result) { - Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); - return loadObject(type, objectReference.getOid(), null, page, task, result); - } - - @Nullable - public static PrismObject loadObject(Class type, String oid, - PageBase page, Task task, OperationResult result) { - return loadObject(type, oid, null, page, task, result); - } - - @Nullable - public static PrismObject loadObject(Class type, String oid, - Collection> options, - PageBase page, Task task, OperationResult result) { - return loadObject(type, oid, options, true, page, task, result); - } - - @Nullable - public static PrismObject loadObject(Class type, String oid, - Collection> options, boolean allowNotFound, - PageBase page, Task task, OperationResult result) { - LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); - } else { - subResult = new OperationResult(OPERATION_LOAD_OBJECT); - } - PrismObject object = null; - try { - if (options == null) { - options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); - } else { - GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); - if (getOpts == null) { - options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); - } else { - getOpts.setResolveNames(Boolean.TRUE); - } - } - object = page.getModelService().getObject(type, oid, options, task, subResult); - } catch (AuthorizationException e) { - // Not authorized to access the object. This is probably caused by a reference that - // point to an object that the current user cannot read. This is no big deal. - // Just do not display that object. - subResult.recordHandledError(e); - LOGGER.debug("User {} is not authorized to read {} {}", - task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); - return null; - } catch (ObjectNotFoundException e) { - if (allowNotFound) { - // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. - subResult.recordHandledError(e); - LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); - return null; - } else { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), e); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", e); - } - } catch (Exception ex) { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - } finally { - subResult.computeStatus(); - } - // TODO reconsider this part: until recently, the condition was always 'false' - if (WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Loaded {} with result {}", object, subResult); - - return object; - } - - //TODO consider using modelServiceLocator instead of PageBase in other methods.. Do we even need it? What about showResult? Should it be - // here or directly in the page? Consider usability and readabiltiy - @Nullable - public static PrismObject loadObject(ObjectReferenceType objectReference, - ModelServiceLocator page, Task task, OperationResult result) { - Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); - String oid = objectReference.getOid(); - Collection> options = null; - LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); - } else { - subResult = new OperationResult(OPERATION_LOAD_OBJECT); - } - PrismObject object = null; - try { - if (options == null) { - options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); - } else { - GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); - if (getOpts == null) { - options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); - } else { - getOpts.setResolveNames(Boolean.TRUE); - } - } - object = page.getModelService().getObject(type, oid, options, task, subResult); - } catch (AuthorizationException e) { - // Not authorized to access the object. This is probably caused by a reference that - // point to an object that the current user cannot read. This is no big deal. - // Just do not display that object. - subResult.recordHandledError(e); - LOGGER.debug("User {} is not authorized to read {} {}", - task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); - return null; - } catch (ObjectNotFoundException e) { - // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. - subResult.recordHandledError(e); - LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); - return null; - - } catch (Exception ex) { - subResult.recordFatalError("WebModelUtils.couldntLoadObject", ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - } finally { - subResult.computeStatus(); - } - // TODO reconsider this part: until recently, the condition was always 'false' - if (WebComponentUtil.showResultInPage(subResult)) { - if (page instanceof PageBase) { - ((PageBase)page).showResult(subResult); - } - } - - LOGGER.debug("Loaded {} with result {}", object, subResult); - - return object; - } - - public static boolean isNoFetch(Collection> options) { - if (options == null) { - return false; - } - GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); - if (rootOptions == null) { - return false; - } - return GetOperationOptions.isNoFetch(rootOptions); - } - - @NotNull - public static List> searchObjects( - Class type, ObjectQuery query, OperationResult result, PageBase page) { - return searchObjects(type, query, null, result, page, null); - } - - @NotNull - public static List> searchObjects(Class type, ObjectQuery query, - Collection> options, - OperationResult result, PageBase page) { - return searchObjects(type, query, options, result, page, null); - } - - @NotNull - public static List> searchObjects( - Class type, ObjectQuery query, Collection> options, - OperationResult result, PageBase page, PrismObject principal) { - LOGGER.debug("Searching {} with oid {}, options {}", type.getSimpleName(), query, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_SEARCH_OBJECTS); - } else { - subResult = new OperationResult(OPERATION_SEARCH_OBJECTS); - } - List> objects = new ArrayList<>(); - try { - Task task = createSimpleTask(subResult.getOperation(), principal, page.getTaskManager()); - List> list = page.getModelService().searchObjects(type, query, options, task, subResult); - if (list != null) { - objects.addAll(list); - } - } catch (Exception ex) { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntSearchObjects").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't search objects", ex); - } finally { - subResult.computeStatus(); - } - - if (result == null && WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Loaded ({}) with result {}", objects.size(), subResult); - - return objects; - } - - public static int countObjects(Class type, ObjectQuery query, PageBase page) { - LOGGER.debug("Count object: type => {}, query => {}", type, query); - Task task = page.createSimpleTask(OPERATION_COUNT_OBJECT); - OperationResult parentResult = new OperationResult(OPERATION_COUNT_OBJECT); - int count = 0; - try { - count = page.getModelService().countObjects(type, query, null, task, parentResult); - } catch (SchemaException | ObjectNotFoundException | SecurityViolationException - | ConfigurationException | CommunicationException | ExpressionEvaluationException ex) { - parentResult.recordFatalError(page.createStringResource("WebModelUtils.couldntCountObjects").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't count objects", ex); - } - - LOGGER.debug("Count objects with result {}", parentResult); - return count; - } - - public static void deleteObject(Class type, String oid, OperationResult result, - PageBase page) { - deleteObject(type, oid, null, result, page, null); - } - - public static void deleteObject(Class type, String oid, ModelExecuteOptions options, - OperationResult result, PageBase page) { - deleteObject(type, oid, options, result, page, null); - } - - public static void deleteObject(Class type, String oid, ModelExecuteOptions options, - OperationResult result, PageBase page, - PrismObject principal) { - LOGGER.debug("Deleting {} with oid {}, options {}", type.getSimpleName(), oid, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_DELETE_OBJECT); - } else { - subResult = new OperationResult(OPERATION_DELETE_OBJECT); - } - try { - Task task = createSimpleTask(result.getOperation(), principal, page.getTaskManager()); - - ObjectDelta delta = page.getPrismContext().deltaFactory().object().create(type, ChangeType.DELETE); - delta.setOid(oid); - - page.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), options, task, subResult); - } catch (Exception ex) { - subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntDeleteObject").getString(), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete object", ex); - } finally { - subResult.computeStatus(); - } - - if (result == null && WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Deleted with result {}", result); - } - - public static Collection> createOptionsForParentOrgRefs(GetOperationOptionsBuilder builder) { - return builder - .item(ObjectType.F_PARENT_ORG_REF).retrieve() - .build(); - } - - public static void save(ObjectDelta delta, OperationResult result, PageBase page) { - save(delta, result, null, page); - } - - public static void save(ObjectDelta delta, OperationResult result, Task task, PageBase page) { - save(delta, null, result, task, page); - } - - public static void save(ObjectDelta delta, ModelExecuteOptions options, OperationResult result, Task task, PageBase page) { - save(WebComponentUtil.createDeltaCollection(delta), options, result, task, page); - } - - - public static void save(Collection> deltas, ModelExecuteOptions options, - OperationResult result, Task task, PageBase page) { - LOGGER.debug("Saving deltas {}, options {}", deltas, options); - - OperationResult subResult; - if (result != null) { - subResult = result.createMinorSubresult(OPERATION_SAVE_OBJECT); - } else { - subResult = new OperationResult(OPERATION_SAVE_OBJECT); - } - - try { - if (task == null) { - task = page.createSimpleTask(result.getOperation()); - } - - page.getModelService().executeChanges(deltas, options, task, result); - } catch (Exception ex) { - subResult.recordFatalError(ex.getMessage()); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save object", ex); - } finally { - subResult.computeStatus(); - } - - if (result == null && WebComponentUtil.showResultInPage(subResult)) { - page.showResult(subResult); - } - - LOGGER.debug("Saved with result {}", subResult); - } - - public static ObjectDelta createActivationAdminStatusDelta( - Class type, String oid, boolean enabled, PrismContext context) { - - ItemPath path = SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; - ActivationStatusType status = enabled ? ActivationStatusType.ENABLED : ActivationStatusType.DISABLED; - ObjectDelta objectDelta = context.deltaFactory().object().createModificationReplaceProperty(type, oid, path, - status); - - return objectDelta; - } - - public static FocusType getLoggedInFocus() { - MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); - Validate.notNull(principal, "No principal"); - if (principal.getFocus() == null) { - throw new IllegalArgumentException("No focus in principal: " + principal); - } - return principal.getFocus(); - } - - public static String getLoggedInFocusOid() { - MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); - Validate.notNull(principal, "No principal"); - if (principal.getOid() == null) { - throw new IllegalArgumentException("No OID in principal: "+principal); - } - return principal.getOid(); - } - - public static Locale getLocale() { - return getLocale(null); - } - - public static Locale getLocale(FocusType focus) { - MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); - Locale locale = null; - if (principal != null) { - if (focus == null) { - PrismObject focusPrismObject = principal.getFocus().asPrismObject(); - focus = focusPrismObject == null ? null : focusPrismObject.asObjectable(); - } - if (focus != null && focus.getPreferredLanguage() != null && - !focus.getPreferredLanguage().trim().equals("")) { - try { - locale = LocaleUtils.toLocale(focus.getPreferredLanguage()); - } catch (Exception ex) { - LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage()); - } - } - if (locale != null && MidPointApplication.containsLocale(locale)) { - return locale; - } else { - String userLocale = focus != null ? focus.getLocale() : null; - try { - locale = userLocale == null ? null : LocaleUtils.toLocale(userLocale); - } catch (Exception ex) { - LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage()); - } - if (locale != null && MidPointApplication.containsLocale(locale)) { - return locale; - } else { - //session in tests is null - if (ThreadContext.getSession() == null) { - return MidPointApplication.getDefaultLocale(); - } - - locale = Session.get().getLocale(); - if (locale == null || !MidPointApplication.containsLocale(locale)) { - //default locale for web application - return MidPointApplication.getDefaultLocale(); - } - return locale; - } - } - } - return MidPointApplication.getDefaultLocale(); - } - - public static TimeZone getTimezone() { - return getTimezone(null); - } - - public static TimeZone getTimezone(FocusType focus) { - GuiProfiledPrincipal principal = SecurityUtils.getPrincipalUser(); - if (principal != null && focus == null) { - focus = principal.getFocus(); - } - String timeZone; - - if (focus != null && StringUtils.isNotEmpty(focus.getTimezone())) { - timeZone = focus.getTimezone(); - } else { - timeZone = principal != null && principal.getCompiledGuiProfile() != null ? - principal.getCompiledGuiProfile().getDefaultTimezone() : ""; - } - try { - if (timeZone != null) { - return TimeZone.getTimeZone(timeZone); - } - } catch (Exception ex){ - LOGGER.debug("Error occurred while getting user time zone, " + ex.getMessage()); - } - return null; - } - - public static Task createSimpleTask(String operation, PrismObject owner, TaskManager manager) { - return createSimpleTask(operation, null, owner, manager); - } - - public static Task createSimpleTask(String operation, String channel, PrismObject owner, TaskManager manager) { - Task task = manager.createTaskInstance(operation); - - if (owner == null) { - MidPointPrincipal user = SecurityUtils.getPrincipalUser(); - if (user == null) { - throw new RestartResponseException(PageLogin.class); - } else { - owner = user.getFocus().asPrismObject(); - } - } - - task.setOwner(owner); - if (channel == null) { - task.setChannel(SchemaConstants.CHANNEL_GUI_USER_URI); - } else { - task.setChannel(channel); - } - - return task; - } - - public static PrismObject reconstructObject(Class type, - String oid, String eventIdentifier, Task task, OperationResult result){ - try { - MidPointApplication application = (MidPointApplication) MidPointApplication.get(); - return application.getAuditService().reconstructObject(type, oid, eventIdentifier, task, result); - } catch (Exception ex){ - LOGGER.debug("Error occurred while reconsructing the object, " + ex.getMessage()); - } - return null; - } - - public static Collection> createLookupTableRetrieveOptions(SchemaHelper schemaHelper) { - return schemaHelper.getOperationOptionsBuilder() - .item(LookupTableType.F_ROW) - .retrieveQuery() - .asc(LookupTableRowType.F_LABEL) - .end() - .build(); - } - - public static ActivationStatusType getAssignmentEffectiveStatus(String lifecycleStatus, ActivationType activationType, PageBase pageBase){ - return pageBase.getModelInteractionService().getAssignmentEffectiveStatus(lifecycleStatus, activationType); - } - - public static void assumePowerOfAttorney(PrismObject donor, - ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { - Task task = taskManager.createTaskInstance(); - OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_ASSUME_POWER_OF_ATTORNEY); - - try { - modelInteractionService.assumePowerOfAttorney(donor, task, result); - } catch (CommonException ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't assume power of attorney", ex); - result.recordFatalError("WebModelUtils.couldntAssumePowerAttorney", ex); - } finally { - result.computeStatusIfUnknown(); - } - } - - public static void dropPowerOfAttorney(ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { - Task task = taskManager.createTaskInstance(); - OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_DROP_POWER_OF_ATTORNEY); - - try { - modelInteractionService.dropPowerOfAttorney(task, result); - } catch (CommonException ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't drop power of attorney", ex); - result.recordFatalError("WebModelUtils.couldntDropPowerAttorney", ex); - } finally { - result.computeStatusIfUnknown(); - } - } - - public static boolean isEnableExperimentalFeature(Task task, ModelServiceLocator pageBase) { - OperationResult result = task.getResult(); - - ModelInteractionService mInteractionService = pageBase.getModelInteractionService(); - - CompiledGuiProfile adminGuiConfig = null; - try { - adminGuiConfig = mInteractionService.getCompiledGuiProfile(task, result); - result.recomputeStatus(); - result.recordSuccessIfUnknown(); - } catch (Exception e) { - LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); - result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); - - } - - if (adminGuiConfig == null) { - return false; - } - - return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); - - } - - public static boolean isEnableExperimentalFeature(ModelInteractionService modelInteractionService, Task task, OperationResult result) { - CompiledGuiProfile adminGuiConfig = null; - try { - adminGuiConfig = modelInteractionService.getCompiledGuiProfile(task, result); - result.recomputeStatus(); - result.recordSuccessIfUnknown(); - } catch (Exception e) { - LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); - result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); - - } - - if (adminGuiConfig == null) { - return false; - } - - return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); - - } - - public static boolean isEnableExperimentalFeature(ModelServiceLocator pageBase) { - Task task = pageBase.createSimpleTask("Load admin gui config"); - return isEnableExperimentalFeature(task, pageBase); - - } - - public static AccessCertificationConfigurationType getCertificationConfiguration(PageBase pageBase) { - OperationResult result = new OperationResult(WebModelServiceUtils.class.getName() + ".getCertificationConfiguration"); - try { - return pageBase.getModelInteractionService().getCertificationConfiguration(result); - } catch (Throwable t) { - LoggingUtils.logUnexpectedException(LOGGER, "Cannot load certification configuration", t); - return null; - } - } - - public static String translateMessage(OperationResult result, ModelServiceLocator page) { - LocalizationService service = page.getLocalizationService(); - Locale locale = page.getLocale(); - - return service.translate(result.getUserFriendlyMessage(), locale); - } - - public static boolean isPostAuthenticationEnabled(TaskManager taskManager, ModelInteractionService modelInteractionService) { - MidPointPrincipal midpointPrincipal = SecurityUtils.getPrincipalUser(); - if (midpointPrincipal != null) { - FocusType focus = midpointPrincipal.getFocus(); - Task task = taskManager.createTaskInstance(OPERATION_LOAD_FLOW_POLICY); - OperationResult parentResult = new OperationResult(OPERATION_LOAD_FLOW_POLICY); - RegistrationsPolicyType registrationPolicyType; - try { - registrationPolicyType = modelInteractionService.getFlowPolicy(focus.asPrismObject(), task, parentResult); - if (registrationPolicyType == null) { - return false; - } - SelfRegistrationPolicyType postAuthenticationPolicy = registrationPolicyType.getPostAuthentication(); - if (postAuthenticationPolicy == null) { - return false; - } - String requiredLifecycleState = postAuthenticationPolicy.getRequiredLifecycleState(); - if (StringUtils.isNotBlank(requiredLifecycleState) && requiredLifecycleState.equals(focus.getLifecycleState())) { - return true; - } - } catch (CommonException e) { - LoggingUtils.logException(LOGGER, "Cannot determine post authentication policies", e); - } - } - return false; - } - - public static PrismObject loadSystemConfigurationAsPrismObject(PageBase pageBase, Task task, OperationResult result) { - PrismObject systemConfig = loadObject( - SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, - pageBase, task, result); - - return systemConfig; - } - -} +/* + * 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.gui.api.util; + +import static com.evolveum.midpoint.schema.GetOperationOptions.createNoFetchCollection; + +import java.util.*; + +import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.LocaleUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.apache.wicket.RestartResponseException; +import org.apache.wicket.Session; +import org.apache.wicket.ThreadContext; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + +import com.evolveum.midpoint.common.LocalizationService; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.api.ModelInteractionService; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismObjectDefinition; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.GetOperationOptionsBuilder; +import com.evolveum.midpoint.schema.SchemaHelper; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.security.api.MidPointPrincipal; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.task.api.TaskManager; +import com.evolveum.midpoint.util.exception.AuthorizationException; +import com.evolveum.midpoint.util.exception.CommonException; +import com.evolveum.midpoint.util.exception.CommunicationException; +import com.evolveum.midpoint.util.exception.ConfigurationException; +import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; +import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; +import com.evolveum.midpoint.util.exception.ObjectNotFoundException; +import com.evolveum.midpoint.util.exception.PolicyViolationException; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.page.login.PageLogin; +import com.evolveum.midpoint.web.security.MidPointApplication; +import com.evolveum.midpoint.web.security.util.SecurityUtils; +import com.evolveum.prism.xml.ns._public.types_3.EvaluationTimeType; + +import javax.xml.namespace.QName; + +/** + * Utility class that contains methods that interact with ModelService and other + * midPoint components. + * + * @author lazyman + */ +public class WebModelServiceUtils { + + private static final Trace LOGGER = TraceManager.getTrace(WebModelServiceUtils.class); + + private static final String DOT_CLASS = WebModelServiceUtils.class.getName() + "."; + private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; + private static final String OPERATION_DELETE_OBJECT = DOT_CLASS + "deleteObject"; + private static final String OPERATION_SEARCH_OBJECTS = DOT_CLASS + "searchObjects"; + private static final String OPERATION_SAVE_OBJECT = DOT_CLASS + "saveObject"; + private static final String OPERATION_LOAD_OBJECT_REFS = DOT_CLASS + "loadObjectReferences"; + private static final String OPERATION_COUNT_OBJECT = DOT_CLASS + "countObjects"; + private static final String OPERATION_ASSUME_POWER_OF_ATTORNEY = DOT_CLASS + "assumePowerOfAttorney"; + private static final String OPERATION_DROP_POWER_OF_ATTORNEY = DOT_CLASS + "dropPowerOfAttorney"; + private static final String OPERATION_GET_SYSTEM_CONFIG = DOT_CLASS + "getSystemConfiguration"; + private static final String OPERATION_LOAD_FLOW_POLICY = DOT_CLASS + "loadFlowPolicy"; + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page) { + return resolveReferenceName(ref, page, false); + } + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, boolean translate) { + Task task = page.createSimpleTask(WebModelServiceUtils.class.getName() + ".resolveReferenceName"); + return resolveReferenceName(ref, page, task, task.getResult(), translate); + } + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result) { + return resolveReferenceName(ref, page, task, result, false); + } + + public static String resolveReferenceName(ObjectReferenceType ref, PageBase page, Task task, OperationResult result, boolean translate) { + if (ref == null) { + return null; + } + if (ref.getTargetName() != null) { + return translate ? page.getLocalizationService().translate(ref.getTargetName().toPolyString(), page.getLocale(), true) + : ref.getTargetName().getOrig(); + } + if (StringUtils.isEmpty(ref.getOid()) || ref.getType() == null){ + return null; + } + PrismObject object = resolveReferenceNoFetch(ref, page, task, result); + if (object == null) { + return ref.getOid(); + } else { + ref.asReferenceValue().setObject(object); + return WebComponentUtil.getName(object, translate); + } + } + + public static PrismObject resolveReferenceNoFetch(ObjectReferenceType reference, PageBase page, Task task, OperationResult result) { + if (reference == null) { + return null; + } + if (reference.asReferenceValue().getObject() != null) { + return reference.asReferenceValue().getObject(); + } + PrismContext prismContext = page.getPrismContext(); + if (reference.getType() == null) { + LOGGER.error("No type in {}", reference); + return null; + } + PrismObjectDefinition definition = prismContext.getSchemaRegistry().findObjectDefinitionByType(reference.getType()); + if (definition == null) { + LOGGER.error("No definition for {} was found", reference.getType()); + return null; + } + if (reference.getOid() == null) { + if (reference.getResolutionTime() == EvaluationTimeType.RUN) { + // Runtime reference resolution. Ignore it for now. Later we maybe would want to resolve it here. + // But it may resolve to several objects .... + return null; + } else { + LOGGER.error("Null OID in reference {}", reference); + // Throw an exception instead? Maybe not. We want GUI to be robust. + return null; + } + } + return loadObject(definition.getCompileTimeClass(), reference.getOid(), createNoFetchCollection(), page, task, result); + } + + public static List createObjectReferenceList(Class type, PageBase page, Map referenceMap){ + referenceMap.clear(); + + OperationResult result = new OperationResult(OPERATION_LOAD_OBJECT_REFS); +// Task task = page.createSimpleTask(OPERATION_LOAD_PASSWORD_POLICIES); + + try { + List> objects = searchObjects(type, null, result, page); + result.recomputeStatus(); + List references = new ArrayList<>(); + + for(PrismObject object: objects){ + referenceMap.put(object.getOid(), WebComponentUtil.getName(object)); + references.add(ObjectTypeUtil.createObjectRef(object, page.getPrismContext())); + + } + return references; + } catch (Exception e){ + result.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadPasswordPolicies").getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load password policies", e); + } + + // TODO - show error somehow + // if(!result.isSuccess()){ + // getPageBase().showResult(result); + // } + + return null; + } + + public static String runTask(TaskType taskToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ + try { + ObjectDelta delta = DeltaFactory.Object.createAddDelta(taskToRun.asPrismObject()); + pageBase.getPrismContext().adopt(delta); + pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, + operationalTask, parentResult); + parentResult.recordInProgress(); + parentResult.setBackgroundTaskOid(delta.getOid()); + pageBase.showResult(parentResult); + return delta.getOid(); + } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException + | ExpressionEvaluationException | CommunicationException | ConfigurationException + | PolicyViolationException | SecurityViolationException e) { + // TODO Auto-generated catch block +// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); + parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); + return null; + } + + } + + public static void runTask(Collection tasksToRun, Task operationalTask, OperationResult parentResult, PageBase pageBase){ +// try { + + for (TaskType taskToRun : tasksToRun){ + runTask(tasksToRun, operationalTask, parentResult, pageBase); + } + +// } +// ObjectDelta delta = ObjectDelta.createAddDelta(taskToRun.asPrismObject()); +// pageBase.getPrismContext().adopt(delta); +// pageBase.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), null, +// operationalTask, parentResult); +// parentResult.recordInProgress(); +// parentResult.setBackgroundTaskOid(delta.getOid()); +// pageBase.showResult(parentResult); +// return delta.getOid(); +// } catch (ObjectAlreadyExistsException | ObjectNotFoundException | SchemaException +// | ExpressionEvaluationException | CommunicationException | ConfigurationException +// | PolicyViolationException | SecurityViolationException e) { +// // TODO Auto-generated catch block +//// error(pageBase.getString("pageUsers.message.nothingSelected") + e.getMessage()); +// parentResult.recordFatalError(pageBase.createStringResource("WebModelUtils.couldntRunTask", e.getMessage()).getString(), e); +// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't run task " + e.getMessage(), e); +// return null; +// } + + } + + public static PrismObject loadObject(PrismReferenceValue objectRef, QName expectedTargetType, PageBase pageBase, Task task, OperationResult result) { + if (objectRef == null) { + return null; + } + + if (QNameUtil.match(expectedTargetType, objectRef.getTargetType())) { + Class type = pageBase.getPrismContext().getSchemaRegistry().determineClassForType(objectRef.getTargetType()); + PrismObject resourceType = WebModelServiceUtils.loadObject(type, objectRef.getOid(), GetOperationOptions.createNoFetchCollection(), pageBase, task, result); + return resourceType; + } + + return null; + } + + @Nullable + public static PrismObject loadObject(ObjectReferenceType objectReference, + PageBase page, Task task, OperationResult result) { + Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); + return loadObject(type, objectReference.getOid(), null, page, task, result); + } + + @Nullable + public static PrismObject loadObject(Class type, String oid, + PageBase page, Task task, OperationResult result) { + return loadObject(type, oid, null, page, task, result); + } + + @Nullable + public static PrismObject loadObject(Class type, String oid, + Collection> options, + PageBase page, Task task, OperationResult result) { + return loadObject(type, oid, options, true, page, task, result); + } + + @Nullable + public static PrismObject loadObject(Class type, String oid, + Collection> options, boolean allowNotFound, + PageBase page, Task task, OperationResult result) { + LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); + } else { + subResult = new OperationResult(OPERATION_LOAD_OBJECT); + } + PrismObject object = null; + try { + if (options == null) { + options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); + } else { + GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); + if (getOpts == null) { + options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); + } else { + getOpts.setResolveNames(Boolean.TRUE); + } + } + object = page.getModelService().getObject(type, oid, options, task, subResult); + } catch (AuthorizationException e) { + // Not authorized to access the object. This is probably caused by a reference that + // point to an object that the current user cannot read. This is no big deal. + // Just do not display that object. + subResult.recordHandledError(e); + LOGGER.debug("User {} is not authorized to read {} {}", + task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); + return null; + } catch (ObjectNotFoundException e) { + if (allowNotFound) { + // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. + subResult.recordHandledError(e); + LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); + return null; + } else { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", e); + } + } catch (Exception ex) { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntLoadObject").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + } finally { + subResult.computeStatus(); + } + // TODO reconsider this part: until recently, the condition was always 'false' + if (WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Loaded {} with result {}", object, subResult); + + return object; + } + + //TODO consider using modelServiceLocator instead of PageBase in other methods.. Do we even need it? What about showResult? Should it be + // here or directly in the page? Consider usability and readabiltiy + @Nullable + public static PrismObject loadObject(ObjectReferenceType objectReference, + ModelServiceLocator page, Task task, OperationResult result) { + Class type = page.getPrismContext().getSchemaRegistry().determineClassForType(objectReference.getType()); + String oid = objectReference.getOid(); + Collection> options = null; + LOGGER.debug("Loading {} with oid {}, options {}", type.getSimpleName(), oid, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_LOAD_OBJECT); + } else { + subResult = new OperationResult(OPERATION_LOAD_OBJECT); + } + PrismObject object = null; + try { + if (options == null) { + options = SelectorOptions.createCollection(GetOperationOptions.createResolveNames()); + } else { + GetOperationOptions getOpts = SelectorOptions.findRootOptions(options); + if (getOpts == null) { + options.add(new SelectorOptions<>(GetOperationOptions.createResolveNames())); + } else { + getOpts.setResolveNames(Boolean.TRUE); + } + } + object = page.getModelService().getObject(type, oid, options, task, subResult); + } catch (AuthorizationException e) { + // Not authorized to access the object. This is probably caused by a reference that + // point to an object that the current user cannot read. This is no big deal. + // Just do not display that object. + subResult.recordHandledError(e); + LOGGER.debug("User {} is not authorized to read {} {}", + task.getOwner() != null ? task.getOwner().getName() : null, type.getSimpleName(), oid); + return null; + } catch (ObjectNotFoundException e) { + // Object does not exist. It was deleted in the meanwhile, or not created yet. This could happen quite often. + subResult.recordHandledError(e); + LOGGER.debug("{} {} does not exist", type.getSimpleName(), oid, e); + return null; + + } catch (Exception ex) { + subResult.recordFatalError("WebModelUtils.couldntLoadObject", ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + } finally { + subResult.computeStatus(); + } + // TODO reconsider this part: until recently, the condition was always 'false' + if (WebComponentUtil.showResultInPage(subResult)) { + if (page instanceof PageBase) { + ((PageBase)page).showResult(subResult); + } + } + + LOGGER.debug("Loaded {} with result {}", object, subResult); + + return object; + } + + public static boolean isNoFetch(Collection> options) { + if (options == null) { + return false; + } + GetOperationOptions rootOptions = SelectorOptions.findRootOptions(options); + if (rootOptions == null) { + return false; + } + return GetOperationOptions.isNoFetch(rootOptions); + } + + @NotNull + public static List> searchObjects( + Class type, ObjectQuery query, OperationResult result, PageBase page) { + return searchObjects(type, query, null, result, page, null); + } + + @NotNull + public static List> searchObjects(Class type, ObjectQuery query, + Collection> options, + OperationResult result, PageBase page) { + return searchObjects(type, query, options, result, page, null); + } + + @NotNull + public static List> searchObjects( + Class type, ObjectQuery query, Collection> options, + OperationResult result, PageBase page, PrismObject principal) { + LOGGER.debug("Searching {} with oid {}, options {}", type.getSimpleName(), query, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_SEARCH_OBJECTS); + } else { + subResult = new OperationResult(OPERATION_SEARCH_OBJECTS); + } + List> objects = new ArrayList<>(); + try { + Task task = createSimpleTask(subResult.getOperation(), principal, page.getTaskManager()); + List> list = page.getModelService().searchObjects(type, query, options, task, subResult); + if (list != null) { + objects.addAll(list); + } + } catch (Exception ex) { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntSearchObjects").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't search objects", ex); + } finally { + subResult.computeStatus(); + } + + if (result == null && WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Loaded ({}) with result {}", objects.size(), subResult); + + return objects; + } + + public static int countObjects(Class type, ObjectQuery query, PageBase page) { + LOGGER.debug("Count object: type => {}, query => {}", type, query); + Task task = page.createSimpleTask(OPERATION_COUNT_OBJECT); + OperationResult parentResult = new OperationResult(OPERATION_COUNT_OBJECT); + int count = 0; + try { + count = page.getModelService().countObjects(type, query, null, task, parentResult); + } catch (SchemaException | ObjectNotFoundException | SecurityViolationException + | ConfigurationException | CommunicationException | ExpressionEvaluationException ex) { + parentResult.recordFatalError(page.createStringResource("WebModelUtils.couldntCountObjects").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't count objects", ex); + } + + LOGGER.debug("Count objects with result {}", parentResult); + return count; + } + + public static void deleteObject(Class type, String oid, OperationResult result, + PageBase page) { + deleteObject(type, oid, null, result, page, null); + } + + public static void deleteObject(Class type, String oid, ModelExecuteOptions options, + OperationResult result, PageBase page) { + deleteObject(type, oid, options, result, page, null); + } + + public static void deleteObject(Class type, String oid, ModelExecuteOptions options, + OperationResult result, PageBase page, + PrismObject principal) { + LOGGER.debug("Deleting {} with oid {}, options {}", type.getSimpleName(), oid, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_DELETE_OBJECT); + } else { + subResult = new OperationResult(OPERATION_DELETE_OBJECT); + } + try { + Task task = createSimpleTask(result.getOperation(), principal, page.getTaskManager()); + + ObjectDelta delta = page.getPrismContext().deltaFactory().object().create(type, ChangeType.DELETE); + delta.setOid(oid); + + page.getModelService().executeChanges(WebComponentUtil.createDeltaCollection(delta), options, task, subResult); + } catch (Exception ex) { + subResult.recordFatalError(page.createStringResource("WebModelUtils.couldntDeleteObject").getString(), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't delete object", ex); + } finally { + subResult.computeStatus(); + } + + if (result == null && WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Deleted with result {}", result); + } + + public static Collection> createOptionsForParentOrgRefs(GetOperationOptionsBuilder builder) { + return builder + .item(ObjectType.F_PARENT_ORG_REF).retrieve() + .build(); + } + + public static void save(ObjectDelta delta, OperationResult result, PageBase page) { + save(delta, result, null, page); + } + + public static void save(ObjectDelta delta, OperationResult result, Task task, PageBase page) { + save(delta, null, result, task, page); + } + + public static void save(ObjectDelta delta, ModelExecuteOptions options, OperationResult result, Task task, PageBase page) { + save(WebComponentUtil.createDeltaCollection(delta), options, result, task, page); + } + + + public static void save(Collection> deltas, ModelExecuteOptions options, + OperationResult result, Task task, PageBase page) { + LOGGER.debug("Saving deltas {}, options {}", deltas, options); + + OperationResult subResult; + if (result != null) { + subResult = result.createMinorSubresult(OPERATION_SAVE_OBJECT); + } else { + subResult = new OperationResult(OPERATION_SAVE_OBJECT); + } + + try { + if (task == null) { + task = page.createSimpleTask(result.getOperation()); + } + + page.getModelService().executeChanges(deltas, options, task, result); + } catch (Exception ex) { + subResult.recordFatalError(ex.getMessage()); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't save object", ex); + } finally { + subResult.computeStatus(); + } + + if (result == null && WebComponentUtil.showResultInPage(subResult)) { + page.showResult(subResult); + } + + LOGGER.debug("Saved with result {}", subResult); + } + + public static ObjectDelta createActivationAdminStatusDelta( + Class type, String oid, boolean enabled, PrismContext context) { + + ItemPath path = SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; + ActivationStatusType status = enabled ? ActivationStatusType.ENABLED : ActivationStatusType.DISABLED; + ObjectDelta objectDelta = context.deltaFactory().object().createModificationReplaceProperty(type, oid, path, + status); + + return objectDelta; + } + + public static FocusType getLoggedInFocus() { + MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); + Validate.notNull(principal, "No principal"); + if (principal.getFocus() == null) { + throw new IllegalArgumentException("No focus in principal: " + principal); + } + return principal.getFocus(); + } + + public static String getLoggedInFocusOid() { + MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); + Validate.notNull(principal, "No principal"); + if (principal.getOid() == null) { + throw new IllegalArgumentException("No OID in principal: "+principal); + } + return principal.getOid(); + } + +// public static Locale getLocale() { +// return getLocale(null); +// } + + public static Locale getLocale() { + MidPointPrincipal principal = SecurityUtils.getPrincipalUser(); + if (principal == null) { + return MidPointApplication.getDefaultLocale(); + } + + Locale locale = null; + + F focus = (F) principal.getFocus(); + if (focus == null) { + return MidPointApplication.getDefaultLocale(); + } +// if (principal != null) { +//// if (focus == null) { +// PrismObject focusPrismObject = principal.getFocus().asPrismObject(); +// FocusType focus = focusPrismObject == null ? null : focusPrismObject.asObjectable(); +//// } + String prefLang = focus.getPreferredLanguage(); + if (StringUtils.isBlank(prefLang)) { + prefLang = focus.getLocale(); + } + + try { + locale = LocaleUtils.toLocale(prefLang); + } catch (Exception ex) { + LOGGER.debug("Error occurred while getting user locale, " + ex.getMessage()); + } + + if (locale == null) { + if (ThreadContext.getSession() == null) { + return MidPointApplication.getDefaultLocale(); + } + + locale = Session.get().getLocale(); + } + + if (MidPointApplication.containsLocale(locale)) { + return locale; + } + + return MidPointApplication.getDefaultLocale(); + } + +// public static TimeZone getTimezone() { +// return getTimezone(null); +// } + + public static TimeZone getTimezone() { + GuiProfiledPrincipal principal = SecurityUtils.getPrincipalUser(); + + if (principal == null) { + return null; + } + + FocusType focus = principal.getFocus(); + + String timeZone; + if (focus == null || StringUtils.isEmpty(focus.getTimezone())) { + timeZone = principal.getCompiledGuiProfile().getDefaultTimezone(); + } else { + timeZone = focus.getTimezone(); + } + + if (timeZone == null) { + return null; + } + + try { + return TimeZone.getTimeZone(timeZone); + } catch (Exception ex){ + LOGGER.debug("Error occurred while getting user time zone, " + ex.getMessage()); + return null; + } + + } + + public static Task createSimpleTask(String operation, PrismObject owner, TaskManager manager) { + return createSimpleTask(operation, null, owner, manager); + } + + public static Task createSimpleTask(String operation, String channel, PrismObject owner, TaskManager manager) { + Task task = manager.createTaskInstance(operation); + + if (owner == null) { + MidPointPrincipal user = SecurityUtils.getPrincipalUser(); + if (user == null) { + throw new RestartResponseException(PageLogin.class); + } else { + owner = user.getFocus().asPrismObject(); + } + } + + task.setOwner(owner); + if (channel == null) { + task.setChannel(SchemaConstants.CHANNEL_GUI_USER_URI); + } else { + task.setChannel(channel); + } + + return task; + } + + public static PrismObject reconstructObject(Class type, + String oid, String eventIdentifier, Task task, OperationResult result){ + try { + MidPointApplication application = (MidPointApplication) MidPointApplication.get(); + return application.getAuditService().reconstructObject(type, oid, eventIdentifier, task, result); + } catch (Exception ex){ + LOGGER.debug("Error occurred while reconsructing the object, " + ex.getMessage()); + } + return null; + } + + public static Collection> createLookupTableRetrieveOptions(SchemaHelper schemaHelper) { + return schemaHelper.getOperationOptionsBuilder() + .item(LookupTableType.F_ROW) + .retrieveQuery() + .asc(LookupTableRowType.F_LABEL) + .end() + .build(); + } + + public static ActivationStatusType getAssignmentEffectiveStatus(String lifecycleStatus, ActivationType activationType, PageBase pageBase){ + return pageBase.getModelInteractionService().getAssignmentEffectiveStatus(lifecycleStatus, activationType); + } + + public static void assumePowerOfAttorney(PrismObject donor, + ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { + Task task = taskManager.createTaskInstance(); + OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_ASSUME_POWER_OF_ATTORNEY); + + try { + modelInteractionService.assumePowerOfAttorney(donor, task, result); + } catch (CommonException ex) { + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't assume power of attorney", ex); + result.recordFatalError("WebModelUtils.couldntAssumePowerAttorney", ex); + } finally { + result.computeStatusIfUnknown(); + } + } + + public static void dropPowerOfAttorney(ModelInteractionService modelInteractionService, TaskManager taskManager, OperationResult parentResult) { + Task task = taskManager.createTaskInstance(); + OperationResult result = OperationResult.createSubResultOrNewResult(parentResult, OPERATION_DROP_POWER_OF_ATTORNEY); + + try { + modelInteractionService.dropPowerOfAttorney(task, result); + } catch (CommonException ex) { + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't drop power of attorney", ex); + result.recordFatalError("WebModelUtils.couldntDropPowerAttorney", ex); + } finally { + result.computeStatusIfUnknown(); + } + } + + public static boolean isEnableExperimentalFeature(Task task, ModelServiceLocator pageBase) { + OperationResult result = task.getResult(); + + ModelInteractionService mInteractionService = pageBase.getModelInteractionService(); + + CompiledGuiProfile adminGuiConfig = null; + try { + adminGuiConfig = mInteractionService.getCompiledGuiProfile(task, result); + result.recomputeStatus(); + result.recordSuccessIfUnknown(); + } catch (Exception e) { + LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); + result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); + + } + + if (adminGuiConfig == null) { + return false; + } + + return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); + + } + + public static boolean isEnableExperimentalFeature(ModelInteractionService modelInteractionService, Task task, OperationResult result) { + CompiledGuiProfile adminGuiConfig = null; + try { + adminGuiConfig = modelInteractionService.getCompiledGuiProfile(task, result); + result.recomputeStatus(); + result.recordSuccessIfUnknown(); + } catch (Exception e) { + LoggingUtils.logException(LOGGER, "Cannot load admin gui config", e); + result.recordPartialError("Cannot load admin gui config. Reason: " + e.getLocalizedMessage()); + + } + + if (adminGuiConfig == null) { + return false; + } + + return BooleanUtils.isTrue(adminGuiConfig.isEnableExperimentalFeatures()); + + } + + public static boolean isEnableExperimentalFeature(ModelServiceLocator pageBase) { + Task task = pageBase.createSimpleTask("Load admin gui config"); + return isEnableExperimentalFeature(task, pageBase); + + } + + public static AccessCertificationConfigurationType getCertificationConfiguration(PageBase pageBase) { + OperationResult result = new OperationResult(WebModelServiceUtils.class.getName() + ".getCertificationConfiguration"); + try { + return pageBase.getModelInteractionService().getCertificationConfiguration(result); + } catch (Throwable t) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot load certification configuration", t); + return null; + } + } + + public static String translateMessage(OperationResult result, ModelServiceLocator page) { + LocalizationService service = page.getLocalizationService(); + Locale locale = page.getLocale(); + + return service.translate(result.getUserFriendlyMessage(), locale); + } + + public static boolean isPostAuthenticationEnabled(TaskManager taskManager, ModelInteractionService modelInteractionService) { + MidPointPrincipal midpointPrincipal = SecurityUtils.getPrincipalUser(); + if (midpointPrincipal != null) { + FocusType focus = midpointPrincipal.getFocus(); + Task task = taskManager.createTaskInstance(OPERATION_LOAD_FLOW_POLICY); + OperationResult parentResult = new OperationResult(OPERATION_LOAD_FLOW_POLICY); + RegistrationsPolicyType registrationPolicyType; + try { + registrationPolicyType = modelInteractionService.getFlowPolicy(focus.asPrismObject(), task, parentResult); + if (registrationPolicyType == null) { + return false; + } + SelfRegistrationPolicyType postAuthenticationPolicy = registrationPolicyType.getPostAuthentication(); + if (postAuthenticationPolicy == null) { + return false; + } + String requiredLifecycleState = postAuthenticationPolicy.getRequiredLifecycleState(); + if (StringUtils.isNotBlank(requiredLifecycleState) && requiredLifecycleState.equals(focus.getLifecycleState())) { + return true; + } + } catch (CommonException e) { + LoggingUtils.logException(LOGGER, "Cannot determine post authentication policies", e); + } + } + return false; + } + + public static PrismObject loadSystemConfigurationAsPrismObject(PageBase pageBase, Task task, OperationResult result) { + PrismObject systemConfig = loadObject( + SystemConfigurationType.class, SystemObjectsType.SYSTEM_CONFIGURATION.value(), null, + pageBase, task, result); + + return systemConfig; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java index be0bee01bd3..35a41e5fea7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/AssignmentPanel.java @@ -897,7 +897,7 @@ public void onClick(AjaxRequestTarget target) { if (targetRef != null && targetRef.getValues() != null && targetRef.getValues().size() > 0) { PrismReferenceValueWrapperImpl refWrapper = targetRef.getValues().get(0); if (!StringUtils.isEmpty(refWrapper.getNewValue().getOid())) { - Class targetClass = ObjectTypes.getObjectTypeFromTypeQName(refWrapper.getRealValue().getType()).getClassDefinition(); + Class targetClass = ObjectTypes.getObjectTypeFromTypeQName(refWrapper.getRealValue().getType()).getClassDefinition(); WebComponentUtil.dispatchToObjectDetailsPage(targetClass, refWrapper.getNewValue().getOid(), AssignmentPanel.this, false); } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java index 99c619975b9..4be3e81c3fa 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java @@ -1,1027 +1,956 @@ -/* - * 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.web.page.admin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; - -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.Session; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.protocol.http.WebSession; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; -import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.context.AssignmentPath; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignment; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignmentTarget; -import com.evolveum.midpoint.model.api.context.EvaluatedConstruction; -import com.evolveum.midpoint.model.api.context.ModelContext; -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.OriginType; -import com.evolveum.midpoint.prism.PrismContainerDefinition; -import com.evolveum.midpoint.prism.PrismContainerValue; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; -import com.evolveum.midpoint.prism.PrismReference; -import com.evolveum.midpoint.prism.PrismReferenceDefinition; -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.delta.ContainerDelta; -import com.evolveum.midpoint.prism.delta.DeltaSetTriple; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.delta.ReferenceDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.schema.SchemaRegistry; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.NoFocusNameSchemaException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; -import com.evolveum.midpoint.web.component.prism.show.PagePreviewChanges; -import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; -import com.evolveum.midpoint.web.page.admin.users.component.AssignmentInfoDto; -import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; -import com.evolveum.midpoint.web.security.util.SecurityUtils; -import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; -import com.evolveum.midpoint.web.util.validation.SimpleValidationError; - -public abstract class PageAdminFocus extends PageAdminObjectDetails - implements ProgressReportingAwarePage { - private static final long serialVersionUID = 1L; - - private LoadableModel> projectionModel; - private LoadableModel> delegatedToMeModel; - - private static final String DOT_CLASS = PageAdminFocus.class.getName() + "."; - private static final String OPERATION_RECOMPUTE_ASSIGNMENTS = DOT_CLASS + "recomputeAssignments"; - - private static final String OPERATION_LOAD_SHADOW = DOT_CLASS + "loadShadow"; - - private static final Trace LOGGER = TraceManager.getTrace(PageAdminFocus.class); - - public PageAdminFocus() { - initialize(null); - } - - public PageAdminFocus(PageParameters parameters) { - getPageParameters().overwriteWith(parameters); - initialize(null); - } - - public PageAdminFocus(final PrismObject userToEdit) { - initialize(userToEdit); - } - - public PageAdminFocus(final PrismObject unitToEdit, boolean isNewObject) { - initialize(unitToEdit, isNewObject); - } - - public PageAdminFocus(final PrismObject unitToEdit, boolean isNewObject, boolean isReadonly) { - initialize(unitToEdit, isNewObject, isReadonly); - } - - - @Override - protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - super.initializeModel(objectToEdit, isNewObject, isReadonly); - - projectionModel = new LoadableModel>(false) { - private static final long serialVersionUID = 1L; - - @Override - protected List load() { - return loadShadowWrappers(true); - } - }; - - delegatedToMeModel= new LoadableModel>(false) { - - private static final long serialVersionUID = 1L; - @Override - protected List load() { - return loadDelegatedToMe(); - } - }; - - } - - public LoadableModel> getProjectionModel() { - return projectionModel; - } - - public LoadableModel> getDelegatedToMeModel() { - return delegatedToMeModel; - } - - public List getFocusShadows() { - return projectionModel.getObject(); - } - - protected void reviveModels() throws SchemaException { - super.reviveModels(); - WebComponentUtil.revive(projectionModel, getPrismContext()); - } - - @Override - public void finishProcessing(AjaxRequestTarget target, OperationResult result, boolean returningFromAsync) { - - if (previewRequested) { - finishPreviewProcessing(target, result); - return; - } - if (result.isSuccess() && getDelta() != null && SecurityUtils.getPrincipalUser().getOid().equals(getDelta().getOid())) { - FocusType focus = null; - if (getObjectWrapper().getObject().asObjectable() instanceof UserType){ - focus = getObjectWrapper().getObject().asObjectable(); - } - Session.get().setLocale(WebModelServiceUtils.getLocale(focus)); - LOGGER.debug("Using {} as locale", getLocale()); - WebSession.get().getClientInfo().getProperties(). - setTimeZone(WebModelServiceUtils.getTimezone(focus)); - LOGGER.debug("Using {} as time zone", WebSession.get().getClientInfo().getProperties().getTimeZone()); - } - boolean focusAddAttempted = getDelta() != null && getDelta().isAdd(); - boolean focusAddSucceeded = focusAddAttempted && StringUtils.isNotEmpty(getDelta().getOid()); - - // we don't want to allow resuming editing if a new focal object was created (on second 'save' there would be a conflict with itself) - // and also in case of partial errors, like those related to projections (many deltas would be already executed, and this could cause problems on second 'save'). - boolean canContinueEditing = !focusAddSucceeded && result.isFatalError(); - - boolean canExitPage; - if (returningFromAsync) { - canExitPage = getProgressPanel().isAllSuccess() || result.isInProgress() || result.isHandledError(); // if there's at least a warning in the progress table, we would like to keep the table open - } else { - canExitPage = !canContinueEditing; // no point in staying on page if we cannot continue editing (in synchronous case i.e. no progress table present) - } - - if (!isKeepDisplayingResults() && canExitPage) { - showResult(result); - redirectBack(); - } else { - if (returningFromAsync) { - getProgressPanel().showBackButton(target); - getProgressPanel().hideAbortButton(target); - } - showResult(result); - target.add(getFeedbackPanel()); - - if (canContinueEditing) { - getProgressPanel().hideBackButton(target); - getProgressPanel().showContinueEditingButton(target); - } - } - } - - private void finishPreviewProcessing(AjaxRequestTarget target, OperationResult result) { - getMainPanel().setVisible(true); - getProgressPanel().hide(); - getProgressPanel().hideAbortButton(target); - getProgressPanel().hideBackButton(target); - getProgressPanel().hideContinueEditingButton(target); - - showResult(result); - target.add(getFeedbackPanel()); - - Map, ModelContext> modelContextMap = new LinkedHashMap<>(); - modelContextMap.put(getObjectWrapper().getObject(), getProgressPanel().getPreviewResult()); - - processAdditionalFocalObjectsForPreview(modelContextMap); - - navigateToNext(new PagePreviewChanges(modelContextMap, getModelInteractionService())); - } - - protected void processAdditionalFocalObjectsForPreview(Map, ModelContext> modelContextMap){ - } - - @Override - public void continueEditing(AjaxRequestTarget target) { - getMainPanel().setVisible(true); - getProgressPanel().hide(); - getProgressPanel().hideAbortButton(target); - getProgressPanel().hideBackButton(target); - getProgressPanel().hideContinueEditingButton(target); - target.add(this); - } - - private List loadShadowWrappers(boolean noFetch) { - List list = new ArrayList<>(); - - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismObject focus = focusWrapper.getObject(); - PrismReference prismReference = focus.findReference(UserType.F_LINK_REF); - if (prismReference == null || prismReference.isEmpty()) { - return new ArrayList<>(); - } - List references = prismReference.getValues(); - - Task task = createSimpleTask(OPERATION_LOAD_SHADOW); - for (PrismReferenceValue reference : references) { - if(reference == null || (reference.getOid() == null && reference.getTargetType() == null)) { - LOGGER.trace("Skiping reference for shadow with null oid"); - continue; // default value - } - OperationResult subResult = task.getResult().createMinorSubresult(OPERATION_LOAD_SHADOW); - PrismObject projection = getPrismObjectForWrapper(ShadowType.class, reference.getOid(), - noFetch, task, subResult, createLoadOptionForShadowWrapper()); - - if(projection == null) { -// showResult(subResult, "pageAdminFocus.message.couldntLoadShadowProjection"); - LOGGER.error("Couldn't load shadow projection"); - continue; - } - - try { - ShadowWrapper wrapper = loadShadowWrapper(projection, task, subResult); - wrapper.setLoadWithNoFetch(noFetch); - - if (wrapper != null) { - list.add((ShadowWrapper)wrapper); - } else { - showResult(subResult, "pageAdminFocus.message.shadowWrapperIsNull"); - LOGGER.error("ShadowWrapper is null"); - } - - //TODO catch Exception/Runtim,eException, Throwable - } catch (SchemaException e) { - showResult(subResult, "pageAdminFocus.message.couldntCreateShadowWrapper"); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't create shadow wrapper", e); - } - } - return list; - } - - private Collection> createLoadOptionForShadowWrapper(){ - return getSchemaHelper().getOperationOptionsBuilder() - .item(ShadowType.F_RESOURCE_REF).resolve().readOnly() - .build(); - } - - public ShadowWrapper loadShadowWrapper(PrismObject projection, Task task, OperationResult result) throws SchemaException{ - PrismObjectWrapperFactory factory = getRegistry().getObjectWrapperFactory(projection.getDefinition()); - WrapperContext context = new WrapperContext(task, result); - context.setCreateIfEmpty(false); - ShadowWrapper wrapper = (ShadowWrapper) factory.createObjectWrapper(projection, ItemStatus.NOT_CHANGED, context); - wrapper.setProjectionStatus(UserDtoStatus.MODIFY); - return wrapper; - } - - public void loadFullShadow(PrismObjectValueWrapper shadowWrapperValue, AjaxRequestTarget target) { - if(shadowWrapperValue.getRealValue() == null) { - error(getString("pageAdminFocus.message.couldntCreateShadowWrapper")); - LOGGER.error("Couldn't create shadow wrapper, because RealValue is null in " + shadowWrapperValue); - return; - } - String oid = shadowWrapperValue.getRealValue().getOid(); - Task task = createSimpleTask(OPERATION_LOAD_SHADOW); - OperationResult result = task.getResult(); - PrismObject projection = getPrismObjectForWrapper(ShadowType.class, oid, false, task, - result, createLoadOptionForShadowWrapper()); - - if (projection == null) { - result.recordFatalError(getString("PageAdminFocus.message.loadFullShadow.fatalError", shadowWrapperValue.getRealValue())); - showResult(result); - target.add(getFeedbackPanel()); - return; - } - - ShadowWrapper shadowWrapperNew; - try { - shadowWrapperNew = loadShadowWrapper(projection, task, result); - - if (shadowWrapperNew == null) { - error(getString("pageAdminFocus.message.shadowWrapperIsNull")); - LOGGER.error("ShadowWrapper is null"); - return; - } - - shadowWrapperValue.getItems().clear(); - shadowWrapperValue.getItems().addAll((Collection) shadowWrapperNew.getValue().getItems()); - ((ShadowWrapper)shadowWrapperValue.getParent()).setLoadWithNoFetch(false); - } catch (SchemaException e) { - error(getString("pageAdminFocus.message.couldntCreateShadowWrapper")); - LOGGER.error("Couldn't create shadow wrapper", e); - } - } - -// @Override -// protected List> loadOrgWrappers() { -// return loadSubwrappers(OrgType.class, UserType.F_PARENT_ORG_REF, false); -// } - -// private List> loadSubwrappers(Class type, -// ItemName propertyToLoad, boolean noFetch) { -// List> list = new ArrayList<>(); -// -// PrismObjectWrapper focusWrapper = getObjectModel().getObject(); -// PrismObject focus = focusWrapper.getObject(); -// PrismReference prismReference = focus.findReference(propertyToLoad); -// if (prismReference == null) { -// return new ArrayList<>(); -// } -// List references = prismReference.getValues(); -// -// Task task = createSimpleTask(OPERATION_LOAD_SHADOW); -// for (PrismReferenceValue reference : references) { -// FocusSubwrapperDto subWrapper = loadSubWrapperDto(type, reference.getOid(), noFetch, task); -// if (subWrapper != null) { -// list.add(subWrapper); -// } -// } -// -// return list; -// } - - private PrismObject getPrismObjectForWrapper(Class type, String oid, boolean noFetch, - Task task, OperationResult subResult, Collection> loadOptions){ - if (oid == null) { - return null; - } - - if (noFetch) { - GetOperationOptions rootOptions = SelectorOptions.findRootOptions(loadOptions); - if (rootOptions == null) { - loadOptions.add(new SelectorOptions<>(GetOperationOptions.createNoFetch())); - } else { - rootOptions.setNoFetch(true); - } - } - - PrismObject projection = WebModelServiceUtils.loadObject(type, oid, loadOptions, this, task, subResult); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Loaded projection {} ({}):\n{}", oid, loadOptions, projection==null?null:projection.debugDump()); - } - - return projection; - } - -// private FocusSubwrapperDto loadSubWrapperDto(Class type, String oid, boolean noFetch, Task task) { -// OperationResult subResult = task.getResult().createMinorSubresult(OPERATION_LOAD_SHADOW); -// Collection> loadOptions = new ArrayList<>(); -// PrismObject projection = getPrismObjectForWrapper(type, oid, noFetch, task, subResult, loadOptions); -// if (projection == null) { -// // No access or error -// // TODO actually it would be nice to show an error if the shadow repo object does not exist -// return null; -// } -// String resourceName = null; -// try { -// S projectionType = projection.asObjectable(); -// -// OperationResultType fetchResult = projectionType.getFetchResult(); -// StringBuilder description = new StringBuilder(); -// if (ShadowType.class.equals(type)) { -// ShadowType shadowType = (ShadowType) projectionType; -// ResourceType resource = shadowType.getResource(); -// resourceName = WebComponentUtil.getName(resource); -// -// if (shadowType.getIntent() != null) { -// description.append(shadowType.getIntent()).append(", "); -// } -// } else if (OrgType.class.equals(type)) { -// OrgType orgType = (OrgType) projectionType; -// resourceName = orgType.getDisplayName() != null -// ? WebComponentUtil.getOrigStringFromPoly(orgType.getDisplayName()) : ""; -// } -// description.append(WebComponentUtil.getOrigStringFromPoly(projectionType.getName())); -// -// ObjectWrapperOld wrapper = ObjectWrapperUtil.createObjectWrapper(resourceName, -// description.toString(), projection, ContainerStatus.MODIFYING, task, this); -// wrapper.setLoadOptions(loadOptions); -// wrapper.setFetchResult(OperationResult.createOperationResult(fetchResult)); -// wrapper.setSelectable(true); -// wrapper.setMinimalized(true); -// -//// wrapper.initializeContainers(this); -// -// subResult.computeStatus(); -// FocusSubwrapperDto ret = new FocusSubwrapperDto<>(wrapper, UserDtoStatus.MODIFY); -// return ret; -// -// } catch (Exception ex) { -// subResult.recordFatalError("Couldn't load account." + ex.getMessage(), ex); -// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load account", ex); -// subResult.computeStatus(); -// return new FocusSubwrapperDto<>(false, resourceName, subResult); -// } -// } - - private List loadDelegatedToMe() { - List list = new ArrayList<>(); - - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismObject focus = focusWrapper.getObject(); - List assignments = focus.asObjectable().getAssignment(); - for (AssignmentType assignment : assignments) { - if (assignment.getTargetRef() != null && - UserType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType())) { - AssignmentEditorDto dto = new AssignmentEditorDto(UserDtoStatus.MODIFY, assignment, this); - dto.setSimpleView(true); - dto.setEditable(false); - list.add(dto); - } - } - - Collections.sort(list); - - return list; - } - - protected List getPolicyRulesList(List assignments, UserDtoStatus status){ - List list = new ArrayList<>(); - for (AssignmentType assignment : assignments) { - if (AssignmentsUtil.isPolicyRuleAssignment(assignment)) { - //TODO set status - list.add(assignment); - } - } - return list; - } - - @Override - protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { - super.prepareObjectForAdd(focus); - F focusType = focus.asObjectable(); - // handle added accounts - - List shadowsToAdd = prepareShadowObject(getFocusShadows()); - for (ShadowType shadowToAdd : shadowsToAdd) { - addDefaultKindAndIntent(shadowToAdd.asPrismObject()); - ObjectReferenceType linkRef = new ObjectReferenceType(); - linkRef.asReferenceValue().setObject(shadowToAdd.asPrismObject()); - focusType.getLinkRef().add(linkRef); - } - -// List orgsToAdd = prepareSubobject(getParentOrgs()); -// if (!orgsToAdd.isEmpty()){ -// focusType.getParentOrg().addAll(orgsToAdd); -// } - - } - - @Override - protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws SchemaException { - super.prepareObjectDeltaForModify(focusDelta); - // handle accounts - PrismObjectDefinition objectDefinition = getObjectDefinition(); - PrismReferenceDefinition refDef = objectDefinition.findReferenceDefinition(FocusType.F_LINK_REF); - ReferenceDelta refDelta = prepareUserAccountsDeltaForModify(refDef); - if (!refDelta.isEmpty()) { - focusDelta.addModification(refDelta); - } - -// refDef = objectDefinition.findReferenceDefinition(FocusType.F_PARENT_ORG_REF); -// refDelta = prepareUserOrgsDeltaForModify(refDef); -// if (!refDelta.isEmpty()) { -// focusDelta.addModification(refDelta); -// } - } - - protected PrismObjectDefinition getObjectDefinition() { - SchemaRegistry registry = getPrismContext().getSchemaRegistry(); - return registry - .findObjectDefinitionByCompileTimeClass(getCompileTimeClass()); - } - - protected ContainerDelta handleAssignmentDeltas(ObjectDelta focusDelta, - List assignments, PrismContainerDefinition def, - boolean isDelegation) throws SchemaException { - ContainerDelta assDelta = getPrismContext().deltaFactory().container().create(ItemPath.EMPTY_PATH, def.getItemName(), def); - - for (AssignmentEditorDto assDto : assignments) { - PrismContainerValue newValue = assDto.getNewValue(getPrismContext()); - - switch (assDto.getStatus()) { - case ADD: - newValue.applyDefinition(def, false); - assDelta.addValueToAdd(newValue.clone()); - break; - case DELETE: - PrismContainerValue oldValue = assDto.getOldValue(); - if (isDelegation){ - oldValue.applyDefinition(def, false); - } else { - oldValue.applyDefinition(def); - } - assDelta.addValueToDelete(oldValue.clone()); - break; - case MODIFY: - if (!assDto.isModified(getPrismContext())) { - LOGGER.trace("Assignment '{}' not modified.", new Object[] { assDto.getName() }); - continue; - } - - handleModifyAssignmentDelta(assDto, def, newValue, focusDelta); - break; - default: - warn(getString("pageAdminUser.message.illegalAssignmentState", assDto.getStatus())); - } - } - - if (!assDelta.isEmpty()) { - assDelta = focusDelta.addModification(assDelta); - } - - return assDelta; - } - - private void handleModifyAssignmentDelta(AssignmentEditorDto assDto, - PrismContainerDefinition assignmentDef, PrismContainerValue newValue, ObjectDelta focusDelta) - throws SchemaException { - LOGGER.debug("Handling modified assignment '{}', computing delta.", - new Object[] { assDto.getName() }); - - PrismValue oldValue = assDto.getOldValue(); - Collection deltas = oldValue.diff(newValue); - - for (ItemDelta delta : deltas) { - ItemPath deltaPath = delta.getPath().rest(); - ItemDefinition deltaDef = assignmentDef.findItemDefinition(deltaPath); - - delta.setParentPath(WebComponentUtil.joinPath(oldValue.getPath(), delta.getPath().allExceptLast())); - delta.applyDefinition(deltaDef); - - focusDelta.addModification(delta); - } - } - - @Override - protected boolean executeForceDelete(PrismObjectWrapper userWrapper, Task task, ModelExecuteOptions options, - OperationResult parentResult) { - if (isForce()) { - OperationResult result = parentResult.createSubresult("Force delete operation"); - - try { - ObjectDelta forceDeleteDelta = getForceDeleteDelta(userWrapper); - forceDeleteDelta.revive(getPrismContext()); - - if (forceDeleteDelta != null && !forceDeleteDelta.isEmpty()) { - getModelService().executeChanges(WebComponentUtil.createDeltaCollection(forceDeleteDelta), - options, task, result); - } - } catch (Exception ex) { - result.recordFatalError(getString("PageAdminFocus.message.executeForceDelete.fatalError")); - LoggingUtils.logUnexpectedException(LOGGER, "Failed to execute delete operation with force", ex); - return false; - } - - result.recomputeStatus(); - result.recordSuccessIfUnknown(); - return true; - } - return false; - } - - private ObjectDelta getForceDeleteDelta(PrismObjectWrapper focusWrapper) throws SchemaException { - - List accounts = getFocusShadows(); - List refDeltas = new ArrayList<>(); - ObjectDelta forceDeleteDelta = null; - for (ShadowWrapper account : accounts) { -// if (!accDto.isLoadedOK()) { -// continue; -// } - if (account.getProjectionStatus() == UserDtoStatus.DELETE) { -// ObjectWrapperOld accWrapper = accDto.getObjectOld(); - ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, - focusWrapper.getObject().getDefinition(), account.getObject()); - refDeltas.add(refDelta); - } else if (account.getProjectionStatus() == UserDtoStatus.UNLINK) { -// ObjectWrapperOld accWrapper = accDto.getObjectOld(); - ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, - focusWrapper.getObject().getDefinition(), account.getObject().getOid()); - refDeltas.add(refDelta); - } - } - if (!refDeltas.isEmpty()) { - forceDeleteDelta = getPrismContext().deltaFactory().object() - .createModifyDelta(focusWrapper.getObject().getOid(), refDeltas, - getCompileTimeClass()); - } - PrismContainerDefinition def = focusWrapper.getObject().findContainer(UserType.F_ASSIGNMENT) - .getDefinition(); - if (forceDeleteDelta == null) { - forceDeleteDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), - focusWrapper.getObject().getOid()); - } - return forceDeleteDelta; - } - -// private

List

prepareSubobject(List> projections) throws SchemaException{ -// List

projectionsToAdd = new ArrayList<>(); -// for (FocusSubwrapperDto

projection : projections) { -// if (!projection.isLoadedOK()) { -// continue; -// } -// -// if (UserDtoStatus.MODIFY.equals(projection.getStatus())) { -// // this is legal e.g. when child org is being create (one assignment comes pre-created) -// // TODO do we need more specific checks here? -// continue; -// } -// -// if (!UserDtoStatus.ADD.equals(projection.getStatus())) { -// warn(getString("pageAdminFocus.message.illegalAccountState", projection.getStatus())); -// continue; -// } -// -// ObjectWrapperOld

projectionWrapper = projection.getObjectOld(); -// ObjectDelta

delta = projectionWrapper.getObjectDelta(); -// PrismObject

proj = delta.getObjectToAdd(); -// WebComponentUtil.encryptCredentials(proj, true, getMidpointApplication()); -// -// projectionsToAdd.add(proj.asObjectable()); -// } -// return projectionsToAdd; -// } - - private List prepareShadowObject(List projections) throws SchemaException{ - List projectionsToAdd = new ArrayList<>(); - for (ShadowWrapper projection : projections) { -// if (!projection.isLoadedOK()) { -// continue; -// } - if (UserDtoStatus.MODIFY.equals(projection.getProjectionStatus())) { - // this is legal e.g. when child org is being create (one assignment comes pre-created) - // TODO do we need more specific checks here? - continue; - } - - if (!UserDtoStatus.ADD.equals(projection.getProjectionStatus())) { - warn(getString("pageAdminFocus.message.illegalAccountState", projection.getStatus())); - continue; - } - - ObjectDelta delta = projection.getObjectDelta(); - PrismObject proj = delta.getObjectToAdd(); - WebComponentUtil.encryptCredentials(proj, true, getMidpointApplication()); - - projectionsToAdd.add(proj.asObjectable()); - } - return projectionsToAdd; - } - - - @Override - protected List> getAdditionalModifyDeltas(OperationResult result) { - return getShadowModifyDeltas(result); - } - - private List> getShadowModifyDeltas(OperationResult result) { - List> deltas = new ArrayList<>(); - - List accounts = getFocusShadows(); - for (ShadowWrapper account : accounts) { -// if (!account.isLoadedOK()) { -// continue; -// } - try { - ObjectDelta delta = account.getObjectDelta(); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Account delta computed from {} as:\n{}", - new Object[] { account, delta.debugDump(3) }); - } - - if (!UserDtoStatus.MODIFY.equals(account.getProjectionStatus())) { - continue; - } - - if (delta == null || delta.isEmpty()) { -// && (accountWrapper.getOldDelta() == null || accountWrapper.getOldDelta().isEmpty())) { - continue; - } - -// if (accountWrapper.getOldDelta() != null) { -// delta = ObjectDeltaCollectionsUtil.summarize(delta, accountWrapper.getOldDelta()); -// } - - - WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Modifying account:\n{}", new Object[] { delta.debugDump(3) }); - } - - deltas.add(delta); - - } catch (Exception ex) { - result.recordFatalError(getString("PageAdminFocus.message.getShadowModifyDeltas.fatalError"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't compute account delta", ex); - } - } - - return deltas; - } - - /** - * remove this method after model is updated - it has to remove resource - * from accountConstruction - */ - @Deprecated - private void removeResourceFromAccConstruction(AssignmentType assignment) { - ConstructionType accConstruction = assignment.getConstruction(); - if (accConstruction == null || accConstruction.getResourceRef() == null || accConstruction.getResourceRef().asReferenceValue().getObject() == null) { - return; - } - - ObjectReferenceType ref = new ObjectReferenceType(); - ref.setOid(assignment.getConstruction().getResourceRef().getOid()); - ref.setType(ResourceType.COMPLEX_TYPE); - assignment.getConstruction().setResourceRef(ref); - } - - private ReferenceDelta prepareUserAccountsDeltaForModify(PrismReferenceDefinition refDef) - throws SchemaException { - ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().create(refDef); - - List accounts = getFocusShadows(); - for (ShadowWrapper accountWrapper : accounts) { -// if (accDto.isLoadedOK()) { -// ObjectWrapperOld accountWrapper = accDto.getObjectOld(); - accountWrapper.revive(getPrismContext()); - ObjectDelta delta = accountWrapper.getObjectDelta(); - PrismReferenceValue refValue = getPrismContext().itemFactory().createReferenceValue(null, OriginType.USER_ACTION, null); - - PrismObject account; - switch (accountWrapper.getProjectionStatus()) { - case ADD: - account = delta.getObjectToAdd(); - addDefaultKindAndIntent(account); - WebComponentUtil.encryptCredentials(account, true, getMidpointApplication()); - refValue.setObject(account); - refDelta.addValueToAdd(refValue); - break; - case DELETE: - account = accountWrapper.getObject(); - refValue.setObject(account); - refDelta.addValueToDelete(refValue); - break; - case MODIFY: - // nothing to do, account modifications were applied - // before - continue; - case UNLINK: - refValue.setOid(delta.getOid()); - refValue.setTargetType(ShadowType.COMPLEX_TYPE); - refDelta.addValueToDelete(refValue); - break; - default: - warn(getString("pageAdminFocus.message.illegalAccountState", accountWrapper.getProjectionStatus())); - } -// } - } - - return refDelta; - } - - private void addDefaultKindAndIntent(PrismObject account) { - if (account.asObjectable().getKind() == null) { - account.asObjectable().setKind(ShadowKindType.ACCOUNT); - } - if (account.asObjectable().getIntent() == null) { - account.asObjectable().setIntent(SchemaConstants.INTENT_DEFAULT); - } - } - - public List showAllAssignmentsPerformed(AjaxRequestTarget ajaxRequestTarget) { - LOGGER.debug("Recompute user assignments"); - Task task = createSimpleTask(OPERATION_RECOMPUTE_ASSIGNMENTS); - OperationResult result = new OperationResult(OPERATION_RECOMPUTE_ASSIGNMENTS); - ObjectDelta delta; - Set assignmentInfoDtoSet = new TreeSet<>(); - - try { - reviveModels(); - - PrismObjectWrapper focusWrapper = getObjectWrapper(); - delta = focusWrapper.getObjectDelta(); -// if (focusWrapper.getOldDelta() != null) { -// delta = ObjectDeltaCollectionsUtil.summarize(focusWrapper.getOldDelta(), delta); -// } - - switch (focusWrapper.getStatus()) { - case ADDED: - PrismObject focus = delta.getObjectToAdd(); - prepareObjectForAdd(focus); - getPrismContext().adopt(focus, getCompileTimeClass()); - - LOGGER.trace("Delta before add focus:\n{}", delta.debugDumpLazily(3)); - if (!delta.isEmpty()) { - delta.revive(getPrismContext()); - } else { - result.recordSuccess(); - } - break; - case NOT_CHANGED: - prepareObjectDeltaForModify(delta); - LOGGER.trace("Delta before modify user:\n{}", delta.debugDumpLazily(3)); - - List> accountDeltas = getShadowModifyDeltas(result); - if (!delta.isEmpty()) { - delta.revive(getPrismContext()); - } - for (ObjectDelta accDelta : accountDeltas) { - if (!accDelta.isEmpty()) { - accDelta.revive(getPrismContext()); - } - } - break; - default: - error(getString("pageAdminFocus.message.unsupportedState", focusWrapper.getStatus())); - } - - ModelContext modelContext; - try { - ModelExecuteOptions options = ModelExecuteOptions.createEvaluateAllAssignmentRelationsOnRecompute(); - modelContext = getModelInteractionService().previewChanges(Collections.singleton(delta), options, task, result); - } catch (NoFocusNameSchemaException e) { - info(getString("pageAdminFocus.message.noUserName")); - ajaxRequestTarget.add(getFeedbackPanel()); - return null; - } - - DeltaSetTriple> evaluatedAssignmentTriple = modelContext.getEvaluatedAssignmentTriple(); - Collection> evaluatedAssignments = null; - if (evaluatedAssignmentTriple != null) { - evaluatedAssignments = evaluatedAssignmentTriple.getNonNegativeValues(); - } - if (evaluatedAssignments == null || evaluatedAssignments.isEmpty()) { - info(getString("pageAdminFocus.message.noAssignmentsAvailable")); - ajaxRequestTarget.add(getFeedbackPanel()); - return null; - } - - for (EvaluatedAssignment evaluatedAssignment : evaluatedAssignments) { - if (!evaluatedAssignment.isValid()) { - continue; - } - // roles and orgs - DeltaSetTriple targetsTriple = evaluatedAssignment.getRoles(); - Collection targets = targetsTriple.getNonNegativeValues(); - for (EvaluatedAssignmentTarget target : targets) { - if (target.getTarget() != null && ArchetypeType.class.equals(target.getTarget().getCompileTimeClass())){ - continue; - } - if (target.appliesToFocusWithAnyRelation(getRelationRegistry())) { - assignmentInfoDtoSet.add(createAssignmentsPreviewDto(target, task, result)); - } - } - - // all resources - DeltaSetTriple evaluatedConstructionsTriple = evaluatedAssignment - .getEvaluatedConstructions(task, result); - Collection evaluatedConstructions = evaluatedConstructionsTriple - .getNonNegativeValues(); - for (EvaluatedConstruction construction : evaluatedConstructions) { - if (!construction.isWeak()) { - assignmentInfoDtoSet.add(createAssignmentsPreviewDto(construction)); - } - } - } - - return new ArrayList<>(assignmentInfoDtoSet); - - } catch (Exception e) { - LoggingUtils.logUnexpectedException(LOGGER, "Could not create assignments preview.", e); - error("Could not create assignments preview. Reason: " + e); - ajaxRequestTarget.add(getFeedbackPanel()); - } - return null; - } - - private AssignmentInfoDto createAssignmentsPreviewDto(EvaluatedAssignmentTarget evaluatedAbstractRole, - Task task, OperationResult result) { - return createAssignmentsPreviewDto(evaluatedAbstractRole.getTarget(), evaluatedAbstractRole.isDirectlyAssigned(), - evaluatedAbstractRole.getAssignmentPath(), evaluatedAbstractRole.getAssignment(), task, result); - } - - protected AssignmentInfoDto createAssignmentsPreviewDto(ObjectReferenceType reference, Task task, OperationResult result) { - PrismObject targetObject = WebModelServiceUtils.resolveReferenceNoFetch(reference, - PageAdminFocus.this, task, result); - return createAssignmentsPreviewDto(targetObject, true, null, null, task, result); - } - - protected AssignmentInfoDto createDelegableAssignmentsPreviewDto(AssignmentType assignment, Task task, OperationResult result) { - if (assignment.getTargetRef() != null) { - if (RoleType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType()) - || OrgType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType()) - || ServiceType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType())) { - PrismObject targetObject = WebModelServiceUtils.resolveReferenceNoFetch(assignment.getTargetRef(), - PageAdminFocus.this, task, result); - Boolean isDelegable = false; - if (targetObject != null) { - isDelegable = targetObject.asObjectable().isDelegable(); - } - if (Boolean.TRUE.equals(isDelegable)) { - return createAssignmentsPreviewDto(targetObject, true, null, assignment, task, result); - } - } - } - return null; - } - - private AssignmentInfoDto createAssignmentsPreviewDto(PrismObject targetObject, - boolean isDirectlyAssigned, AssignmentPath assignmentPath, AssignmentType assignment, - Task task, OperationResult result) { - AssignmentInfoDto dto = new AssignmentInfoDto(); - dto.setTargetOid(targetObject.getOid()); - dto.setTargetName(getNameToDisplay(targetObject)); - dto.setTargetDescription(targetObject.asObjectable().getDescription()); - dto.setTargetClass(targetObject.getCompileTimeClass()); - dto.setTargetType(WebComponentUtil.classToQName(getPrismContext(), targetObject.getCompileTimeClass())); - dto.setDirect(isDirectlyAssigned); - dto.setAssignmentParent(assignmentPath); - if (assignment != null) { - if (assignment.getTenantRef() != null) { - dto.setTenantName(WebModelServiceUtils.resolveReferenceName(assignment.getTenantRef(), PageAdminFocus.this)); - dto.setTenantRef(assignment.getTenantRef()); - } - if (assignment.getOrgRef() != null) { - dto.setOrgRefName(WebModelServiceUtils.resolveReferenceName(assignment.getOrgRef(), PageAdminFocus.this)); - dto.setOrgRef(assignment.getOrgRef()); - } - if (assignment.getTargetRef() != null){ - dto.setRelation(assignment.getTargetRef().getRelation()); - } - } - return dto; - } - - private String getNameToDisplay(PrismObject target) { - if (target.canRepresent(AbstractRoleType.class)) { - String n = PolyString.getOrig(((AbstractRoleType)target.asObjectable()).getDisplayName()); - if (StringUtils.isNotBlank(n)) { - return n; - } - } - return PolyString.getOrig(target.asObjectable().getName()); - } - - private AssignmentInfoDto createAssignmentsPreviewDto(EvaluatedConstruction evaluatedConstruction) { - AssignmentInfoDto dto = new AssignmentInfoDto(); - PrismObject resource = evaluatedConstruction.getResource(); - dto.setTargetOid(resource.getOid()); - dto.setTargetName(PolyString.getOrig(resource.asObjectable().getName())); - dto.setTargetDescription(resource.asObjectable().getDescription()); - dto.setTargetClass(resource.getCompileTimeClass()); - dto.setDirect(evaluatedConstruction.isDirectlyAssigned()); - dto.setAssignmentParent(evaluatedConstruction.getAssignmentPath()); - dto.setKind(evaluatedConstruction.getKind()); - dto.setIntent(evaluatedConstruction.getIntent()); - return dto; - } - - @Override - protected void performAdditionalValidation(PrismObject object, - Collection> deltas, Collection errors) throws SchemaException { - - if (object != null && object.asObjectable() != null) { - for (AssignmentType assignment : object.asObjectable().getAssignment()) { - for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) { - if (errors == null) { - errors = validator.validateAssignment(assignment); - } else { - errors.addAll(validator.validateAssignment(assignment)); - } - } - } - } - - } - - protected boolean isFocusHistoryPage(){ - return false; - } - - protected boolean isSelfProfile(){ - return false; - } -} +/* + * 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.web.page.admin; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Set; +import java.util.TreeSet; + +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.Session; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.protocol.http.WebSession; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; +import com.evolveum.midpoint.gui.impl.factory.WrapperContext; +import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.api.context.AssignmentPath; +import com.evolveum.midpoint.model.api.context.EvaluatedAssignment; +import com.evolveum.midpoint.model.api.context.EvaluatedAssignmentTarget; +import com.evolveum.midpoint.model.api.context.EvaluatedConstruction; +import com.evolveum.midpoint.model.api.context.ModelContext; +import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.OriginType; +import com.evolveum.midpoint.prism.PrismContainerDefinition; +import com.evolveum.midpoint.prism.PrismContainerValue; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismObjectDefinition; +import com.evolveum.midpoint.prism.PrismReference; +import com.evolveum.midpoint.prism.PrismReferenceDefinition; +import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.PrismValue; +import com.evolveum.midpoint.prism.delta.ContainerDelta; +import com.evolveum.midpoint.prism.delta.DeltaSetTriple; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.polystring.PolyString; +import com.evolveum.midpoint.prism.schema.SchemaRegistry; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.exception.NoFocusNameSchemaException; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; +import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; +import com.evolveum.midpoint.web.component.prism.show.PagePreviewChanges; +import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; +import com.evolveum.midpoint.web.page.admin.users.component.AssignmentInfoDto; +import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; +import com.evolveum.midpoint.web.security.util.SecurityUtils; +import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; +import com.evolveum.midpoint.web.util.validation.SimpleValidationError; + +public abstract class PageAdminFocus extends PageAdminObjectDetails + implements ProgressReportingAwarePage { + private static final long serialVersionUID = 1L; + + private LoadableModel> projectionModel; + private LoadableModel> delegatedToMeModel; + + private static final String DOT_CLASS = PageAdminFocus.class.getName() + "."; + private static final String OPERATION_RECOMPUTE_ASSIGNMENTS = DOT_CLASS + "recomputeAssignments"; + + private static final String OPERATION_LOAD_SHADOW = DOT_CLASS + "loadShadow"; + + private static final Trace LOGGER = TraceManager.getTrace(PageAdminFocus.class); + + public PageAdminFocus() { + initialize(null); + } + + public PageAdminFocus(PageParameters parameters) { + getPageParameters().overwriteWith(parameters); + initialize(null); + } + + public PageAdminFocus(final PrismObject userToEdit) { + initialize(userToEdit); + } + + public PageAdminFocus(final PrismObject unitToEdit, boolean isNewObject) { + initialize(unitToEdit, isNewObject); + } + + public PageAdminFocus(final PrismObject unitToEdit, boolean isNewObject, boolean isReadonly) { + initialize(unitToEdit, isNewObject, isReadonly); + } + + + @Override + protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { + super.initializeModel(objectToEdit, isNewObject, isReadonly); + + projectionModel = new LoadableModel>(false) { + private static final long serialVersionUID = 1L; + + @Override + protected List load() { + return loadShadowWrappers(true); + } + }; + + delegatedToMeModel= new LoadableModel>(false) { + + private static final long serialVersionUID = 1L; + @Override + protected List load() { + return loadDelegatedToMe(); + } + }; + + } + + public LoadableModel> getProjectionModel() { + return projectionModel; + } + + public LoadableModel> getDelegatedToMeModel() { + return delegatedToMeModel; + } + + public List getFocusShadows() { + return projectionModel.getObject(); + } + + protected void reviveModels() throws SchemaException { + super.reviveModels(); + WebComponentUtil.revive(projectionModel, getPrismContext()); + } + + @Override + public void continueEditing(AjaxRequestTarget target) { + getMainPanel().setVisible(true); + getProgressPanel().hide(); + getProgressPanel().hideAbortButton(target); + getProgressPanel().hideBackButton(target); + getProgressPanel().hideContinueEditingButton(target); + target.add(this); + } + + private List loadShadowWrappers(boolean noFetch) { + List list = new ArrayList<>(); + + PrismObjectWrapper focusWrapper = getObjectModel().getObject(); + PrismObject focus = focusWrapper.getObject(); + PrismReference prismReference = focus.findReference(UserType.F_LINK_REF); + if (prismReference == null || prismReference.isEmpty()) { + return new ArrayList<>(); + } + List references = prismReference.getValues(); + + Task task = createSimpleTask(OPERATION_LOAD_SHADOW); + for (PrismReferenceValue reference : references) { + if(reference == null || (reference.getOid() == null && reference.getTargetType() == null)) { + LOGGER.trace("Skiping reference for shadow with null oid"); + continue; // default value + } + OperationResult subResult = task.getResult().createMinorSubresult(OPERATION_LOAD_SHADOW); + PrismObject projection = getPrismObjectForWrapper(ShadowType.class, reference.getOid(), + noFetch, task, subResult, createLoadOptionForShadowWrapper()); + + if(projection == null) { +// showResult(subResult, "pageAdminFocus.message.couldntLoadShadowProjection"); + LOGGER.error("Couldn't load shadow projection"); + continue; + } + + try { + ShadowWrapper wrapper = loadShadowWrapper(projection, task, subResult); + wrapper.setLoadWithNoFetch(noFetch); + + if (wrapper != null) { + list.add((ShadowWrapper)wrapper); + } else { + showResult(subResult, "pageAdminFocus.message.shadowWrapperIsNull"); + LOGGER.error("ShadowWrapper is null"); + } + + //TODO catch Exception/Runtim,eException, Throwable + } catch (SchemaException e) { + showResult(subResult, "pageAdminFocus.message.couldntCreateShadowWrapper"); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't create shadow wrapper", e); + } + } + return list; + } + + private Collection> createLoadOptionForShadowWrapper(){ + return getSchemaHelper().getOperationOptionsBuilder() + .item(ShadowType.F_RESOURCE_REF).resolve().readOnly() + .build(); + } + + public ShadowWrapper loadShadowWrapper(PrismObject projection, Task task, OperationResult result) throws SchemaException{ + PrismObjectWrapperFactory factory = getRegistry().getObjectWrapperFactory(projection.getDefinition()); + WrapperContext context = new WrapperContext(task, result); + context.setCreateIfEmpty(false); + ShadowWrapper wrapper = (ShadowWrapper) factory.createObjectWrapper(projection, ItemStatus.NOT_CHANGED, context); + wrapper.setProjectionStatus(UserDtoStatus.MODIFY); + return wrapper; + } + + public void loadFullShadow(PrismObjectValueWrapper shadowWrapperValue, AjaxRequestTarget target) { + if(shadowWrapperValue.getRealValue() == null) { + error(getString("pageAdminFocus.message.couldntCreateShadowWrapper")); + LOGGER.error("Couldn't create shadow wrapper, because RealValue is null in " + shadowWrapperValue); + return; + } + String oid = shadowWrapperValue.getRealValue().getOid(); + Task task = createSimpleTask(OPERATION_LOAD_SHADOW); + OperationResult result = task.getResult(); + PrismObject projection = getPrismObjectForWrapper(ShadowType.class, oid, false, task, + result, createLoadOptionForShadowWrapper()); + + if (projection == null) { + result.recordFatalError(getString("PageAdminFocus.message.loadFullShadow.fatalError", shadowWrapperValue.getRealValue())); + showResult(result); + target.add(getFeedbackPanel()); + return; + } + + ShadowWrapper shadowWrapperNew; + try { + shadowWrapperNew = loadShadowWrapper(projection, task, result); + + if (shadowWrapperNew == null) { + error(getString("pageAdminFocus.message.shadowWrapperIsNull")); + LOGGER.error("ShadowWrapper is null"); + return; + } + + shadowWrapperValue.getItems().clear(); + shadowWrapperValue.getItems().addAll((Collection) shadowWrapperNew.getValue().getItems()); + ((ShadowWrapper)shadowWrapperValue.getParent()).setLoadWithNoFetch(false); + } catch (SchemaException e) { + error(getString("pageAdminFocus.message.couldntCreateShadowWrapper")); + LOGGER.error("Couldn't create shadow wrapper", e); + } + } + +// @Override +// protected List> loadOrgWrappers() { +// return loadSubwrappers(OrgType.class, UserType.F_PARENT_ORG_REF, false); +// } + +// private List> loadSubwrappers(Class type, +// ItemName propertyToLoad, boolean noFetch) { +// List> list = new ArrayList<>(); +// +// PrismObjectWrapper focusWrapper = getObjectModel().getObject(); +// PrismObject focus = focusWrapper.getObject(); +// PrismReference prismReference = focus.findReference(propertyToLoad); +// if (prismReference == null) { +// return new ArrayList<>(); +// } +// List references = prismReference.getValues(); +// +// Task task = createSimpleTask(OPERATION_LOAD_SHADOW); +// for (PrismReferenceValue reference : references) { +// FocusSubwrapperDto subWrapper = loadSubWrapperDto(type, reference.getOid(), noFetch, task); +// if (subWrapper != null) { +// list.add(subWrapper); +// } +// } +// +// return list; +// } + + private PrismObject getPrismObjectForWrapper(Class type, String oid, boolean noFetch, + Task task, OperationResult subResult, Collection> loadOptions){ + if (oid == null) { + return null; + } + + if (noFetch) { + GetOperationOptions rootOptions = SelectorOptions.findRootOptions(loadOptions); + if (rootOptions == null) { + loadOptions.add(new SelectorOptions<>(GetOperationOptions.createNoFetch())); + } else { + rootOptions.setNoFetch(true); + } + } + + PrismObject projection = WebModelServiceUtils.loadObject(type, oid, loadOptions, this, task, subResult); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Loaded projection {} ({}):\n{}", oid, loadOptions, projection==null?null:projection.debugDump()); + } + + return projection; + } + +// private FocusSubwrapperDto loadSubWrapperDto(Class type, String oid, boolean noFetch, Task task) { +// OperationResult subResult = task.getResult().createMinorSubresult(OPERATION_LOAD_SHADOW); +// Collection> loadOptions = new ArrayList<>(); +// PrismObject projection = getPrismObjectForWrapper(type, oid, noFetch, task, subResult, loadOptions); +// if (projection == null) { +// // No access or error +// // TODO actually it would be nice to show an error if the shadow repo object does not exist +// return null; +// } +// String resourceName = null; +// try { +// S projectionType = projection.asObjectable(); +// +// OperationResultType fetchResult = projectionType.getFetchResult(); +// StringBuilder description = new StringBuilder(); +// if (ShadowType.class.equals(type)) { +// ShadowType shadowType = (ShadowType) projectionType; +// ResourceType resource = shadowType.getResource(); +// resourceName = WebComponentUtil.getName(resource); +// +// if (shadowType.getIntent() != null) { +// description.append(shadowType.getIntent()).append(", "); +// } +// } else if (OrgType.class.equals(type)) { +// OrgType orgType = (OrgType) projectionType; +// resourceName = orgType.getDisplayName() != null +// ? WebComponentUtil.getOrigStringFromPoly(orgType.getDisplayName()) : ""; +// } +// description.append(WebComponentUtil.getOrigStringFromPoly(projectionType.getName())); +// +// ObjectWrapperOld wrapper = ObjectWrapperUtil.createObjectWrapper(resourceName, +// description.toString(), projection, ContainerStatus.MODIFYING, task, this); +// wrapper.setLoadOptions(loadOptions); +// wrapper.setFetchResult(OperationResult.createOperationResult(fetchResult)); +// wrapper.setSelectable(true); +// wrapper.setMinimalized(true); +// +//// wrapper.initializeContainers(this); +// +// subResult.computeStatus(); +// FocusSubwrapperDto ret = new FocusSubwrapperDto<>(wrapper, UserDtoStatus.MODIFY); +// return ret; +// +// } catch (Exception ex) { +// subResult.recordFatalError("Couldn't load account." + ex.getMessage(), ex); +// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load account", ex); +// subResult.computeStatus(); +// return new FocusSubwrapperDto<>(false, resourceName, subResult); +// } +// } + + private List loadDelegatedToMe() { + List list = new ArrayList<>(); + + PrismObjectWrapper focusWrapper = getObjectModel().getObject(); + PrismObject focus = focusWrapper.getObject(); + List assignments = focus.asObjectable().getAssignment(); + for (AssignmentType assignment : assignments) { + if (assignment.getTargetRef() != null && + UserType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType())) { + AssignmentEditorDto dto = new AssignmentEditorDto(UserDtoStatus.MODIFY, assignment, this); + dto.setSimpleView(true); + dto.setEditable(false); + list.add(dto); + } + } + + Collections.sort(list); + + return list; + } + + protected List getPolicyRulesList(List assignments, UserDtoStatus status){ + List list = new ArrayList<>(); + for (AssignmentType assignment : assignments) { + if (AssignmentsUtil.isPolicyRuleAssignment(assignment)) { + //TODO set status + list.add(assignment); + } + } + return list; + } + + @Override + protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { + super.prepareObjectForAdd(focus); + F focusType = focus.asObjectable(); + // handle added accounts + + List shadowsToAdd = prepareShadowObject(getFocusShadows()); + for (ShadowType shadowToAdd : shadowsToAdd) { + addDefaultKindAndIntent(shadowToAdd.asPrismObject()); + ObjectReferenceType linkRef = new ObjectReferenceType(); + linkRef.asReferenceValue().setObject(shadowToAdd.asPrismObject()); + focusType.getLinkRef().add(linkRef); + } + +// List orgsToAdd = prepareSubobject(getParentOrgs()); +// if (!orgsToAdd.isEmpty()){ +// focusType.getParentOrg().addAll(orgsToAdd); +// } + + } + + @Override + protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws SchemaException { + super.prepareObjectDeltaForModify(focusDelta); + // handle accounts + PrismObjectDefinition objectDefinition = getObjectDefinition(); + PrismReferenceDefinition refDef = objectDefinition.findReferenceDefinition(FocusType.F_LINK_REF); + ReferenceDelta refDelta = prepareUserAccountsDeltaForModify(refDef); + if (!refDelta.isEmpty()) { + focusDelta.addModification(refDelta); + } + +// refDef = objectDefinition.findReferenceDefinition(FocusType.F_PARENT_ORG_REF); +// refDelta = prepareUserOrgsDeltaForModify(refDef); +// if (!refDelta.isEmpty()) { +// focusDelta.addModification(refDelta); +// } + } + + protected PrismObjectDefinition getObjectDefinition() { + SchemaRegistry registry = getPrismContext().getSchemaRegistry(); + return registry + .findObjectDefinitionByCompileTimeClass(getCompileTimeClass()); + } + + protected ContainerDelta handleAssignmentDeltas(ObjectDelta focusDelta, + List assignments, PrismContainerDefinition def, + boolean isDelegation) throws SchemaException { + ContainerDelta assDelta = getPrismContext().deltaFactory().container().create(ItemPath.EMPTY_PATH, def.getItemName(), def); + + for (AssignmentEditorDto assDto : assignments) { + PrismContainerValue newValue = assDto.getNewValue(getPrismContext()); + + switch (assDto.getStatus()) { + case ADD: + newValue.applyDefinition(def, false); + assDelta.addValueToAdd(newValue.clone()); + break; + case DELETE: + PrismContainerValue oldValue = assDto.getOldValue(); + if (isDelegation){ + oldValue.applyDefinition(def, false); + } else { + oldValue.applyDefinition(def); + } + assDelta.addValueToDelete(oldValue.clone()); + break; + case MODIFY: + if (!assDto.isModified(getPrismContext())) { + LOGGER.trace("Assignment '{}' not modified.", new Object[] { assDto.getName() }); + continue; + } + + handleModifyAssignmentDelta(assDto, def, newValue, focusDelta); + break; + default: + warn(getString("pageAdminUser.message.illegalAssignmentState", assDto.getStatus())); + } + } + + if (!assDelta.isEmpty()) { + assDelta = focusDelta.addModification(assDelta); + } + + return assDelta; + } + + private void handleModifyAssignmentDelta(AssignmentEditorDto assDto, + PrismContainerDefinition assignmentDef, PrismContainerValue newValue, ObjectDelta focusDelta) + throws SchemaException { + LOGGER.debug("Handling modified assignment '{}', computing delta.", + new Object[] { assDto.getName() }); + + PrismValue oldValue = assDto.getOldValue(); + Collection deltas = oldValue.diff(newValue); + + for (ItemDelta delta : deltas) { + ItemPath deltaPath = delta.getPath().rest(); + ItemDefinition deltaDef = assignmentDef.findItemDefinition(deltaPath); + + delta.setParentPath(WebComponentUtil.joinPath(oldValue.getPath(), delta.getPath().allExceptLast())); + delta.applyDefinition(deltaDef); + + focusDelta.addModification(delta); + } + } + + @Override + protected boolean executeForceDelete(PrismObjectWrapper userWrapper, Task task, ModelExecuteOptions options, + OperationResult parentResult) { + if (isForce()) { + OperationResult result = parentResult.createSubresult("Force delete operation"); + + try { + ObjectDelta forceDeleteDelta = getForceDeleteDelta(userWrapper); + forceDeleteDelta.revive(getPrismContext()); + + if (forceDeleteDelta != null && !forceDeleteDelta.isEmpty()) { + getModelService().executeChanges(WebComponentUtil.createDeltaCollection(forceDeleteDelta), + options, task, result); + } + } catch (Exception ex) { + result.recordFatalError(getString("PageAdminFocus.message.executeForceDelete.fatalError")); + LoggingUtils.logUnexpectedException(LOGGER, "Failed to execute delete operation with force", ex); + return false; + } + + result.recomputeStatus(); + result.recordSuccessIfUnknown(); + return true; + } + return false; + } + + private ObjectDelta getForceDeleteDelta(PrismObjectWrapper focusWrapper) throws SchemaException { + + List accounts = getFocusShadows(); + List refDeltas = new ArrayList<>(); + ObjectDelta forceDeleteDelta = null; + for (ShadowWrapper account : accounts) { +// if (!accDto.isLoadedOK()) { +// continue; +// } + if (account.getProjectionStatus() == UserDtoStatus.DELETE) { +// ObjectWrapperOld accWrapper = accDto.getObjectOld(); + ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, + focusWrapper.getObject().getDefinition(), account.getObject()); + refDeltas.add(refDelta); + } else if (account.getProjectionStatus() == UserDtoStatus.UNLINK) { +// ObjectWrapperOld accWrapper = accDto.getObjectOld(); + ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, + focusWrapper.getObject().getDefinition(), account.getObject().getOid()); + refDeltas.add(refDelta); + } + } + if (!refDeltas.isEmpty()) { + forceDeleteDelta = getPrismContext().deltaFactory().object() + .createModifyDelta(focusWrapper.getObject().getOid(), refDeltas, + getCompileTimeClass()); + } + PrismContainerDefinition def = focusWrapper.getObject().findContainer(UserType.F_ASSIGNMENT) + .getDefinition(); + if (forceDeleteDelta == null) { + forceDeleteDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), + focusWrapper.getObject().getOid()); + } + return forceDeleteDelta; + } + +// private

List

prepareSubobject(List> projections) throws SchemaException{ +// List

projectionsToAdd = new ArrayList<>(); +// for (FocusSubwrapperDto

projection : projections) { +// if (!projection.isLoadedOK()) { +// continue; +// } +// +// if (UserDtoStatus.MODIFY.equals(projection.getStatus())) { +// // this is legal e.g. when child org is being create (one assignment comes pre-created) +// // TODO do we need more specific checks here? +// continue; +// } +// +// if (!UserDtoStatus.ADD.equals(projection.getStatus())) { +// warn(getString("pageAdminFocus.message.illegalAccountState", projection.getStatus())); +// continue; +// } +// +// ObjectWrapperOld

projectionWrapper = projection.getObjectOld(); +// ObjectDelta

delta = projectionWrapper.getObjectDelta(); +// PrismObject

proj = delta.getObjectToAdd(); +// WebComponentUtil.encryptCredentials(proj, true, getMidpointApplication()); +// +// projectionsToAdd.add(proj.asObjectable()); +// } +// return projectionsToAdd; +// } + + private List prepareShadowObject(List projections) throws SchemaException{ + List projectionsToAdd = new ArrayList<>(); + for (ShadowWrapper projection : projections) { +// if (!projection.isLoadedOK()) { +// continue; +// } + if (UserDtoStatus.MODIFY.equals(projection.getProjectionStatus())) { + // this is legal e.g. when child org is being create (one assignment comes pre-created) + // TODO do we need more specific checks here? + continue; + } + + if (!UserDtoStatus.ADD.equals(projection.getProjectionStatus())) { + warn(getString("pageAdminFocus.message.illegalAccountState", projection.getStatus())); + continue; + } + + ObjectDelta delta = projection.getObjectDelta(); + PrismObject proj = delta.getObjectToAdd(); + WebComponentUtil.encryptCredentials(proj, true, getMidpointApplication()); + + projectionsToAdd.add(proj.asObjectable()); + } + return projectionsToAdd; + } + + + @Override + protected List> getAdditionalModifyDeltas(OperationResult result) { + return getShadowModifyDeltas(result); + } + + private List> getShadowModifyDeltas(OperationResult result) { + List> deltas = new ArrayList<>(); + + List accounts = getFocusShadows(); + for (ShadowWrapper account : accounts) { +// if (!account.isLoadedOK()) { +// continue; +// } + try { + ObjectDelta delta = account.getObjectDelta(); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Account delta computed from {} as:\n{}", + new Object[] { account, delta.debugDump(3) }); + } + + if (!UserDtoStatus.MODIFY.equals(account.getProjectionStatus())) { + continue; + } + + if (delta == null || delta.isEmpty()) { +// && (accountWrapper.getOldDelta() == null || accountWrapper.getOldDelta().isEmpty())) { + continue; + } + +// if (accountWrapper.getOldDelta() != null) { +// delta = ObjectDeltaCollectionsUtil.summarize(delta, accountWrapper.getOldDelta()); +// } + + + WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Modifying account:\n{}", new Object[] { delta.debugDump(3) }); + } + + deltas.add(delta); + + } catch (Exception ex) { + result.recordFatalError(getString("PageAdminFocus.message.getShadowModifyDeltas.fatalError"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't compute account delta", ex); + } + } + + return deltas; + } + + /** + * remove this method after model is updated - it has to remove resource + * from accountConstruction + */ + @Deprecated + private void removeResourceFromAccConstruction(AssignmentType assignment) { + ConstructionType accConstruction = assignment.getConstruction(); + if (accConstruction == null || accConstruction.getResourceRef() == null || accConstruction.getResourceRef().asReferenceValue().getObject() == null) { + return; + } + + ObjectReferenceType ref = new ObjectReferenceType(); + ref.setOid(assignment.getConstruction().getResourceRef().getOid()); + ref.setType(ResourceType.COMPLEX_TYPE); + assignment.getConstruction().setResourceRef(ref); + } + + private ReferenceDelta prepareUserAccountsDeltaForModify(PrismReferenceDefinition refDef) + throws SchemaException { + ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().create(refDef); + + List accounts = getFocusShadows(); + for (ShadowWrapper accountWrapper : accounts) { +// if (accDto.isLoadedOK()) { +// ObjectWrapperOld accountWrapper = accDto.getObjectOld(); + accountWrapper.revive(getPrismContext()); + ObjectDelta delta = accountWrapper.getObjectDelta(); + PrismReferenceValue refValue = getPrismContext().itemFactory().createReferenceValue(null, OriginType.USER_ACTION, null); + + PrismObject account; + switch (accountWrapper.getProjectionStatus()) { + case ADD: + account = delta.getObjectToAdd(); + addDefaultKindAndIntent(account); + WebComponentUtil.encryptCredentials(account, true, getMidpointApplication()); + refValue.setObject(account); + refDelta.addValueToAdd(refValue); + break; + case DELETE: + account = accountWrapper.getObject(); + refValue.setObject(account); + refDelta.addValueToDelete(refValue); + break; + case MODIFY: + // nothing to do, account modifications were applied + // before + continue; + case UNLINK: + refValue.setOid(delta.getOid()); + refValue.setTargetType(ShadowType.COMPLEX_TYPE); + refDelta.addValueToDelete(refValue); + break; + default: + warn(getString("pageAdminFocus.message.illegalAccountState", accountWrapper.getProjectionStatus())); + } +// } + } + + return refDelta; + } + + private void addDefaultKindAndIntent(PrismObject account) { + if (account.asObjectable().getKind() == null) { + account.asObjectable().setKind(ShadowKindType.ACCOUNT); + } + if (account.asObjectable().getIntent() == null) { + account.asObjectable().setIntent(SchemaConstants.INTENT_DEFAULT); + } + } + + public List showAllAssignmentsPerformed(AjaxRequestTarget ajaxRequestTarget) { + LOGGER.debug("Recompute user assignments"); + Task task = createSimpleTask(OPERATION_RECOMPUTE_ASSIGNMENTS); + OperationResult result = new OperationResult(OPERATION_RECOMPUTE_ASSIGNMENTS); + ObjectDelta delta; + Set assignmentInfoDtoSet = new TreeSet<>(); + + try { + reviveModels(); + + PrismObjectWrapper focusWrapper = getObjectWrapper(); + delta = focusWrapper.getObjectDelta(); +// if (focusWrapper.getOldDelta() != null) { +// delta = ObjectDeltaCollectionsUtil.summarize(focusWrapper.getOldDelta(), delta); +// } + + switch (focusWrapper.getStatus()) { + case ADDED: + PrismObject focus = delta.getObjectToAdd(); + prepareObjectForAdd(focus); + getPrismContext().adopt(focus, getCompileTimeClass()); + + LOGGER.trace("Delta before add focus:\n{}", delta.debugDumpLazily(3)); + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + } else { + result.recordSuccess(); + } + break; + case NOT_CHANGED: + prepareObjectDeltaForModify(delta); + LOGGER.trace("Delta before modify user:\n{}", delta.debugDumpLazily(3)); + + List> accountDeltas = getShadowModifyDeltas(result); + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + } + for (ObjectDelta accDelta : accountDeltas) { + if (!accDelta.isEmpty()) { + accDelta.revive(getPrismContext()); + } + } + break; + default: + error(getString("pageAdminFocus.message.unsupportedState", focusWrapper.getStatus())); + } + + ModelContext modelContext; + try { + ModelExecuteOptions options = ModelExecuteOptions.createEvaluateAllAssignmentRelationsOnRecompute(); + modelContext = getModelInteractionService().previewChanges(Collections.singleton(delta), options, task, result); + } catch (NoFocusNameSchemaException e) { + info(getString("pageAdminFocus.message.noUserName")); + ajaxRequestTarget.add(getFeedbackPanel()); + return null; + } + + DeltaSetTriple> evaluatedAssignmentTriple = modelContext.getEvaluatedAssignmentTriple(); + Collection> evaluatedAssignments = null; + if (evaluatedAssignmentTriple != null) { + evaluatedAssignments = evaluatedAssignmentTriple.getNonNegativeValues(); + } + if (evaluatedAssignments == null || evaluatedAssignments.isEmpty()) { + info(getString("pageAdminFocus.message.noAssignmentsAvailable")); + ajaxRequestTarget.add(getFeedbackPanel()); + return null; + } + + for (EvaluatedAssignment evaluatedAssignment : evaluatedAssignments) { + if (!evaluatedAssignment.isValid()) { + continue; + } + // roles and orgs + DeltaSetTriple targetsTriple = evaluatedAssignment.getRoles(); + Collection targets = targetsTriple.getNonNegativeValues(); + for (EvaluatedAssignmentTarget target : targets) { + if (target.getTarget() != null && ArchetypeType.class.equals(target.getTarget().getCompileTimeClass())){ + continue; + } + if (target.appliesToFocusWithAnyRelation(getRelationRegistry())) { + assignmentInfoDtoSet.add(createAssignmentsPreviewDto(target, task, result)); + } + } + + // all resources + DeltaSetTriple evaluatedConstructionsTriple = evaluatedAssignment + .getEvaluatedConstructions(task, result); + Collection evaluatedConstructions = evaluatedConstructionsTriple + .getNonNegativeValues(); + for (EvaluatedConstruction construction : evaluatedConstructions) { + if (!construction.isWeak()) { + assignmentInfoDtoSet.add(createAssignmentsPreviewDto(construction)); + } + } + } + + return new ArrayList<>(assignmentInfoDtoSet); + + } catch (Exception e) { + LoggingUtils.logUnexpectedException(LOGGER, "Could not create assignments preview.", e); + error("Could not create assignments preview. Reason: " + e); + ajaxRequestTarget.add(getFeedbackPanel()); + } + return null; + } + + private AssignmentInfoDto createAssignmentsPreviewDto(EvaluatedAssignmentTarget evaluatedAbstractRole, + Task task, OperationResult result) { + return createAssignmentsPreviewDto(evaluatedAbstractRole.getTarget(), evaluatedAbstractRole.isDirectlyAssigned(), + evaluatedAbstractRole.getAssignmentPath(), evaluatedAbstractRole.getAssignment(), task, result); + } + + protected AssignmentInfoDto createAssignmentsPreviewDto(ObjectReferenceType reference, Task task, OperationResult result) { + PrismObject targetObject = WebModelServiceUtils.resolveReferenceNoFetch(reference, + PageAdminFocus.this, task, result); + return createAssignmentsPreviewDto(targetObject, true, null, null, task, result); + } + + protected AssignmentInfoDto createDelegableAssignmentsPreviewDto(AssignmentType assignment, Task task, OperationResult result) { + if (assignment.getTargetRef() != null) { + if (RoleType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType()) + || OrgType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType()) + || ServiceType.COMPLEX_TYPE.equals(assignment.getTargetRef().getType())) { + PrismObject targetObject = WebModelServiceUtils.resolveReferenceNoFetch(assignment.getTargetRef(), + PageAdminFocus.this, task, result); + Boolean isDelegable = false; + if (targetObject != null) { + isDelegable = targetObject.asObjectable().isDelegable(); + } + if (Boolean.TRUE.equals(isDelegable)) { + return createAssignmentsPreviewDto(targetObject, true, null, assignment, task, result); + } + } + } + return null; + } + + private AssignmentInfoDto createAssignmentsPreviewDto(PrismObject targetObject, + boolean isDirectlyAssigned, AssignmentPath assignmentPath, AssignmentType assignment, + Task task, OperationResult result) { + AssignmentInfoDto dto = new AssignmentInfoDto(); + dto.setTargetOid(targetObject.getOid()); + dto.setTargetName(getNameToDisplay(targetObject)); + dto.setTargetDescription(targetObject.asObjectable().getDescription()); + dto.setTargetClass(targetObject.getCompileTimeClass()); + dto.setTargetType(WebComponentUtil.classToQName(getPrismContext(), targetObject.getCompileTimeClass())); + dto.setDirect(isDirectlyAssigned); + dto.setAssignmentParent(assignmentPath); + if (assignment != null) { + if (assignment.getTenantRef() != null) { + dto.setTenantName(WebModelServiceUtils.resolveReferenceName(assignment.getTenantRef(), PageAdminFocus.this)); + dto.setTenantRef(assignment.getTenantRef()); + } + if (assignment.getOrgRef() != null) { + dto.setOrgRefName(WebModelServiceUtils.resolveReferenceName(assignment.getOrgRef(), PageAdminFocus.this)); + dto.setOrgRef(assignment.getOrgRef()); + } + if (assignment.getTargetRef() != null){ + dto.setRelation(assignment.getTargetRef().getRelation()); + } + } + return dto; + } + + private String getNameToDisplay(PrismObject target) { + if (target.canRepresent(AbstractRoleType.class)) { + String n = PolyString.getOrig(((AbstractRoleType)target.asObjectable()).getDisplayName()); + if (StringUtils.isNotBlank(n)) { + return n; + } + } + return PolyString.getOrig(target.asObjectable().getName()); + } + + private AssignmentInfoDto createAssignmentsPreviewDto(EvaluatedConstruction evaluatedConstruction) { + AssignmentInfoDto dto = new AssignmentInfoDto(); + PrismObject resource = evaluatedConstruction.getResource(); + dto.setTargetOid(resource.getOid()); + dto.setTargetName(PolyString.getOrig(resource.asObjectable().getName())); + dto.setTargetDescription(resource.asObjectable().getDescription()); + dto.setTargetClass(resource.getCompileTimeClass()); + dto.setDirect(evaluatedConstruction.isDirectlyAssigned()); + dto.setAssignmentParent(evaluatedConstruction.getAssignmentPath()); + dto.setKind(evaluatedConstruction.getKind()); + dto.setIntent(evaluatedConstruction.getIntent()); + return dto; + } + + @Override + protected void performAdditionalValidation(PrismObject object, + Collection> deltas, Collection errors) throws SchemaException { + + if (object != null && object.asObjectable() != null) { + for (AssignmentType assignment : object.asObjectable().getAssignment()) { + for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) { + if (errors == null) { + errors = validator.validateAssignment(assignment); + } else { + errors.addAll(validator.validateAssignment(assignment)); + } + } + } + } + + } + + protected boolean isFocusHistoryPage(){ + return false; + } + + protected boolean isSelfProfile(){ + return false; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java index f82fe7ca9e9..e90588c4372 100755 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java @@ -1,1016 +1,1085 @@ -/* - * Copyright (c) 2010-2018 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.web.page.admin; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.List; - -import javax.xml.namespace.QName; - -import com.evolveum.midpoint.gui.api.component.*; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.util.WebPrismUtil; -import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; -import com.evolveum.midpoint.prism.PrismContainerValue; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.web.component.AjaxButton; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.web.component.util.SelectableBean; -import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.PageSystemConfiguration; -import com.evolveum.midpoint.web.page.admin.server.OperationalButtonsPanel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.Page; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.behavior.Behavior; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.util.string.StringValue; -import org.apache.wicket.util.time.Duration; -import org.jetbrains.annotations.NotNull; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; -import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.ObjectSummaryPanel; -import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; -import com.evolveum.midpoint.web.component.progress.ProgressPanel; -import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.page.admin.users.dto.FocusSubwrapperDto; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; -import com.evolveum.midpoint.web.util.validation.SimpleValidationError; - -/** - * @author semancik - */ -public abstract class PageAdminObjectDetails extends PageAdmin - implements ProgressReportingAwarePage { - private static final long serialVersionUID = 1L; - - private static final String DOT_CLASS = PageAdminObjectDetails.class.getName() + "."; - - public static final String PARAM_RETURN_PAGE = "returnPage"; - - private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; - private static final String OPERATION_LOAD_PARENT_ORGS = DOT_CLASS + "loadParentOrgs"; - private static final String OPERATION_LOAD_GUI_CONFIGURATION = DOT_CLASS + "loadGuiConfiguration"; - protected static final String OPERATION_SAVE = DOT_CLASS + "save"; - protected static final String OPERATION_PREVIEW_CHANGES = DOT_CLASS + "previewChanges"; - protected static final String OPERATION_SEND_TO_SUBMIT = DOT_CLASS + "sendToSubmit"; - protected static final String OPERATION_LOAD_ARCHETYPE_REF = DOT_CLASS + "loadArchetypeRef"; - protected static final String OPERATION_EXECUTE_CHANGES = DOT_CLASS + "executeChangesTask"; - protected static final String OPERATION_EXECUTE_ARCHETYPE_CHANGES = DOT_CLASS + "executeArchetypeChanges"; - protected static final String OPERATION_LOAD_FILTERED_ARCHETYPES = DOT_CLASS + "loadFilteredArchetypes"; - - protected static final String ID_SUMMARY_PANEL = "summaryPanel"; - protected static final String ID_MAIN_PANEL = "mainPanel"; - private static final String ID_PROGRESS_PANEL = "progressPanel"; - private static final String ID_BUTTONS = "buttons"; - - private static final Trace LOGGER = TraceManager.getTrace(PageAdminObjectDetails.class); - - private LoadableModel> objectModel; - private LoadableModel>> parentOrgModel; - - private ProgressPanel progressPanel; - - // used to determine whether to leave this page or stay on it (after - // operation finishing) - private ObjectDelta delta; - - private AbstractObjectMainPanel mainPanel; - private boolean saveOnConfigure; // ugly hack - whether to invoke 'Save' when returning to this page - - private boolean editingFocus = false; //before we got isOidParameterExists status depending only on oid parameter existence - //we should set editingFocus=true not only when oid parameter exists but also - //when object is given as a constructor parameter - - public boolean isEditingFocus() { - return editingFocus; - } - - @Override - protected void createBreadcrumb() { - createInstanceBreadcrumb(); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - if (saveOnConfigure) { - saveOnConfigure = false; - add(new AbstractAjaxTimerBehavior(Duration.milliseconds(100)) { - @Override - protected void onTimer(AjaxRequestTarget target) { - stop(target); - savePerformed(target); - } - }); - } - } - - @Override - protected IModel createPageTitleModel() { - if (PageAdminObjectDetails.this instanceof PageSystemConfiguration){ - return super.createPageTitleModel(); - } - String simpleName = getObjectSimpleName(); - String lokalizedSimpleName = new StringResourceModel("ObjectType." + simpleName).setDefaultValue(simpleName).getString(); - if (isAdd()) { - return createStringResource("PageAdminObjectDetails.title.new", lokalizedSimpleName); - } - - String name = null; - if (getObjectWrapper() != null && getObjectWrapper().getObject() != null) { - name = WebComponentUtil.getName(getObjectWrapper().getObject()); - } - - return createStringResource("PageAdminObjectDetails.title.edit.readonly.${readOnly}", getObjectModel(), lokalizedSimpleName, name); - } - - private String getObjectSimpleName(){ - if (getObjectWrapper() != null && getObjectWrapper().getObject() != null - && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType){ - AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); - DisplayType displayType = WebComponentUtil - .getArchetypePolicyDisplayType(assignmentHolderObj, PageAdminObjectDetails.this); - if (displayType == null){ - ObjectReferenceType archetypeReference = getObjectArchetypeRef(); - if (archetypeReference != null){ - OperationResult result = new OperationResult(OPERATION_LOAD_ARCHETYPE_REF); - Task task = createSimpleTask(OPERATION_LOAD_ARCHETYPE_REF); - PrismObject archetypeObj = WebModelServiceUtils.resolveReferenceNoFetch(archetypeReference, - this, task, result); - displayType = archetypeObj != null && archetypeObj.asObjectable().getArchetypePolicy() != null ? - archetypeObj.asObjectable().getArchetypePolicy().getDisplay() : null; - } - } - if (displayType != null && displayType.getLabel() != null) { - String archetypeLocalizedName = getLocalizationService() - .translate(displayType.getLabel().toPolyString(), WebComponentUtil.getCurrentLocale(), true); - if (StringUtils.isNotEmpty(archetypeLocalizedName)) { - return archetypeLocalizedName; - } - } - } - return getCompileTimeClass().getSimpleName(); - } - - public boolean isAdd() { - return !isOidParameterExists() && !editingFocus; - } - - public LoadableModel> getObjectModel() { - return objectModel; - } - - protected AbstractObjectMainPanel getMainPanel() { - return mainPanel; - } - - public PrismObjectWrapper getObjectWrapper() { - return objectModel.getObject(); - } - - public List> getParentOrgs() { - return parentOrgModel.getObject(); - } - - public ObjectDelta getDelta() { - return delta; - } - - public void setDelta(ObjectDelta delta) { - this.delta = delta; - } - - public ProgressPanel getProgressPanel() { - return progressPanel; - } - - protected void reviveModels() throws SchemaException { - WebComponentUtil.revive(objectModel, getPrismContext()); - WebComponentUtil.revive(parentOrgModel, getPrismContext()); - } - - public abstract Class getCompileTimeClass(); - - - public void initialize(final PrismObject objectToEdit) { - boolean isNewObject = objectToEdit == null && StringUtils.isEmpty(getObjectOidParameter()); - - initialize(objectToEdit, isNewObject, false); - } - - public void initialize(final PrismObject objectToEdit, boolean isNewObject) { - initialize(objectToEdit, isNewObject, false); - } - - public void initialize(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - initializeModel(objectToEdit, isNewObject, isReadonly); -// initLayout(); - } - - protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - editingFocus = !isNewObject; - - objectModel = new LoadableModel>(false) { - private static final long serialVersionUID = 1L; - - @Override - protected PrismObjectWrapper load() { - PrismObjectWrapper wrapper = loadObjectWrapper(objectToEdit, isReadonly); -// wrapper.sort(); - return wrapper; - } - }; - - parentOrgModel = new LoadableModel>>(false) { - private static final long serialVersionUID = 1L; - - @Override - protected List> load() { - return loadOrgWrappers(); - } - }; - } - - private ObjectReferenceType getObjectArchetypeRef() { - ObjectReferenceType archetypeReference = null; - if (getObjectWrapper() != null && getObjectWrapper().getObject() != null - && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType) { - AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); - if (assignmentHolderObj.getAssignment() != null) { - for (AssignmentType assignment : assignmentHolderObj.getAssignment()) { - if (assignment.getTargetRef() != null && assignment.getTargetRef().getType() != null - && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { - archetypeReference = assignment.getTargetRef(); - break; - } - } - } - } - return archetypeReference; - } - - protected List> loadOrgWrappers() { - // WRONG!! TODO: fix - return null; - } - - protected abstract O createNewObject(); - - @Override - protected void onInitialize() { - super.onInitialize(); - initLayout(); - } - - protected void initLayout() { - initLayoutSummaryPanel(); - initOperationalButtonsPanel(); - - mainPanel = createMainPanel(ID_MAIN_PANEL); - mainPanel.setOutputMarkupId(true); - add(mainPanel); - - progressPanel = new ProgressPanel(ID_PROGRESS_PANEL); - add(progressPanel); - } - - protected abstract ObjectSummaryPanel createSummaryPanel(); - - protected void initLayoutSummaryPanel() { - - ObjectSummaryPanel summaryPanel = createSummaryPanel(); - summaryPanel.setOutputMarkupId(true); - - setSummaryPanelVisibility(summaryPanel); - add(summaryPanel); - } - - protected void setSummaryPanelVisibility(ObjectSummaryPanel summaryPanel){ - summaryPanel.add(new VisibleEnableBehaviour() { - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible() { - return isOidParameterExists() || editingFocus; - } - }); - } - - private void initOperationalButtonsPanel(){ - OperationalButtonsPanel opButtonPanel = new OperationalButtonsPanel(ID_BUTTONS) { - private static final long serialVersionUID = 1L; - - @Override - protected void addButtons(RepeatingView repeatingView) { - initOperationalButtons(repeatingView); - } - }; - if (getAdditionalOperationalButtonPanelBehaviors() != null && !getAdditionalOperationalButtonPanelBehaviors().isEmpty()){ - getAdditionalOperationalButtonPanelBehaviors().forEach(this::add); - } - opButtonPanel.setOutputMarkupId(true); - opButtonPanel.add(new VisibleBehaviour(() -> isEditingFocus() && opButtonPanel.buttonsExist())); - add(opButtonPanel); - } - - protected List getAdditionalOperationalButtonPanelBehaviors(){ - return new ArrayList<>(); - } - - protected void initOperationalButtons(RepeatingView repeatingView){ - if (getObjectArchetypeRef() != null) { - AjaxButton changeArchetype = new AjaxButton(repeatingView.newChildId(), createStringResource("PageAdminObjectDetails.button.changeArchetype")) { - @Override - public void onClick(AjaxRequestTarget target) { - changeArchetypeButtonClicked(target); - } - }; - changeArchetype.add(new VisibleBehaviour(() -> getObjectArchetypeRef() != null)); - changeArchetype.add(AttributeAppender.append("class", "btn-default")); - repeatingView.add(changeArchetype); - } - } - - protected OperationalButtonsPanel getOperationalButtonsPanel(){ - return (OperationalButtonsPanel) get(ID_BUTTONS); - } - - private void changeArchetypeButtonClicked(AjaxRequestTarget target){ - - AssignmentPopup changeArchetypePopup = new AssignmentPopup(getMainPopupBodyId()) { - - private static final long serialVersionUID = 1L; - - @Override - protected void addPerformed(AjaxRequestTarget target, List newAssignmentsList) { - super.addPerformed(target, newAssignmentsList); - try { - PrismContainerWrapper assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); - ((List) newAssignmentsList).forEach(assignment -> { - PrismContainerValue newAssignment = assignmentsWrapper.getItem().createNewValue(); - assignmentsWrapper.getValues().forEach(assignmentValue -> { - if (assignmentValue.getRealValue().getTargetRef() != null - && assignmentValue.getRealValue().getTargetRef().getType() != null - && QNameUtil.match(assignmentValue.getRealValue().getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)){ - assignmentValue.setStatus(ValueStatus.DELETED); - } - }); - AssignmentType assignmentType = newAssignment.asContainerable(); - assignmentType.setTargetRef(assignment.getTargetRef()); - WebPrismUtil.createNewValueWrapper(assignmentsWrapper, newAssignment, PageAdminObjectDetails.this, target); - OperationResult result = new OperationResult(OPERATION_EXECUTE_ARCHETYPE_CHANGES); - Task task = createSimpleTask(OPERATION_EXECUTE_ARCHETYPE_CHANGES); - try { - ObjectDelta archetypeDelta = getObjectWrapper().getObjectDelta(); - if (!archetypeDelta.isEmpty()) { - archetypeDelta.revive(getPrismContext()); - getModelService().executeChanges(WebComponentUtil.createDeltaCollection(archetypeDelta), null, task, result); - result.computeStatus(); - } - } catch (Exception e) { - LOGGER.error("Cannot save archetype assignment changes: {}", e.getMessage()); - } - showResult(result); - }); - } catch (SchemaException e) { - LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); - } - target.add(PageAdminObjectDetails.this.getFeedbackPanel()); - } - - @Override - protected List createAssignmentTabs() { - List tabs = new ArrayList<>(); - - tabs.add(new PanelTab(getPageBase().createStringResource("ObjectTypes.ARCHETYPE"), - new VisibleBehaviour(() -> true)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusTypeAssignmentPopupTabPanel(panelId, ObjectTypes.ARCHETYPE) { - private static final long serialVersionUID = 1L; - - @Override - protected PrismContainerWrapper getAssignmentWrapperModel() { - PrismContainerWrapper assignmentsWrapper = null; - try { - assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); - } catch (SchemaException e) { - LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); - } - return assignmentsWrapper; - } - - @Override - protected List getSupportedRelations() { - return Collections.singletonList(SchemaConstants.ORG_DEFAULT); - } - - @Override - protected void onSelectionPerformed(AjaxRequestTarget target, IModel> rowModel) { - target.add(getObjectListPanel()); - tabLabelPanelUpdate(target); - } - - @Override - protected IModel getObjectSelectCheckBoxEnableModel(IModel> rowModel){ - if (rowModel == null){ - return Model.of(false); - } - List selectedObjects = getSelectedObjectsList(); - return Model.of(selectedObjects == null || selectedObjects.size() == 0 - || (rowModel.getObject() != null && rowModel.getObject().isSelected())); - } - - - @Override - protected ObjectTypes getObjectType() { - return ObjectTypes.ARCHETYPE; - } - - @Override - protected ObjectQuery addFilterToContentQuery(ObjectQuery query){ - super.addFilterToContentQuery(query); - if (query == null) { - query = getPrismContext().queryFactory().createQuery(); - } - List archetypeOidsList = getFilteredArchetypeOidsList(); - ObjectFilter filter = getPrismContext().queryFor(ArchetypeType.class) - .id(archetypeOidsList.toArray(new String[0])) - .buildFilter(); - query.addFilter(filter); - return query; - } - }; - } - }); - return tabs; - } - }; - - changeArchetypePopup.setOutputMarkupPlaceholderTag(true); - showMainPopup(changeArchetypePopup, target); - - } - - private List getFilteredArchetypeOidsList(){ - OperationResult result = new OperationResult(OPERATION_LOAD_FILTERED_ARCHETYPES); - PrismObject obj = getObjectWrapper().getObject(); - List oidsList = new ArrayList<>(); - try { - List filteredArchetypes = getModelInteractionService().getFilteredArchetypesByHolderType(obj, result); - if (filteredArchetypes != null){ - filteredArchetypes.forEach(archetype -> oidsList.add(archetype.getOid())); - } - } catch (SchemaException ex){ - result.recordPartialError(ex.getLocalizedMessage()); - LOGGER.error("Couldn't load assignment target specification for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); - } - return oidsList; - } - - protected abstract AbstractObjectMainPanel createMainPanel(String id); - - protected String getObjectOidParameter() { - PageParameters parameters = getPageParameters(); - LOGGER.trace("Page parameters: {}", parameters); - StringValue oidValue = parameters.get(OnePageParameterEncoder.PARAMETER); - LOGGER.trace("OID parameter: {}", oidValue); - if (oidValue == null) { - return null; - } - String oid = oidValue.toString(); - if (StringUtils.isBlank(oid)) { - return null; - } - return oid; - } - - protected ObjectSummaryPanel getSummaryPanel() { - return (ObjectSummaryPanel) get(ID_SUMMARY_PANEL); - } - - public boolean isOidParameterExists() { - return getObjectOidParameter() != null; - } - - protected PrismObjectWrapper loadObjectWrapper(PrismObject objectToEdit, boolean isReadonly) { - Task task = createSimpleTask(OPERATION_LOAD_OBJECT); - OperationResult result = task.getResult(); - PrismObject object = null; - try { - if (!isOidParameterExists()) { - if (objectToEdit == null) { - LOGGER.trace("Loading object: New object (creating)"); - O focusType = createNewObject(); - - // Apply subtype using page parameters - List subtypes = getPageParameters().getValues(ObjectType.F_SUBTYPE.getLocalPart()); - subtypes.stream().filter(p -> !p.isEmpty()).forEach(c -> focusType.subtype(c.toString())); - - getMidpointApplication().getPrismContext().adopt(focusType); - object = (PrismObject) focusType.asPrismObject(); - } else { - LOGGER.trace("Loading object: New object (supplied): {}", objectToEdit); - object = objectToEdit; - } - } else { - - String focusOid = getObjectOidParameter(); - object = WebModelServiceUtils.loadObject(getCompileTimeClass(), focusOid, buildGetOptions(), this, task, result); - LOGGER.trace("Loading object: Existing object (loadled): {} -> {}", focusOid, object); - } - - result.recordSuccess(); - } catch (Exception ex) { - result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - } - - showResult(result, false); - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Loaded object:\n{}", object.debugDump()); - } - - if (object == null) { - if (isOidParameterExists()) { - getSession().error(getString("pageAdminFocus.message.cantEditFocus")); - } else { - getSession().error(getString("pageAdminFocus.message.cantNewFocus")); - } - throw new RestartResponseException(getRestartResponsePage()); - } - - ItemStatus itemStatus = isOidParameterExists() || editingFocus ? ItemStatus.NOT_CHANGED : ItemStatus.ADDED; - PrismObjectWrapper wrapper; - - PrismObjectWrapperFactory factory = getRegistry().getObjectWrapperFactory(object.getDefinition()); - WrapperContext context = new WrapperContext(task, result); - context.setCreateIfEmpty(ItemStatus.ADDED == itemStatus); - //we don't want to set to false.. refactor this method to take either enum (READONLY, AUTO, ...) or - // Boolean instead of boolean isReadonly - if (isReadonly) { - context.setReadOnly(isReadonly); - } - - - try { - wrapper = factory.createObjectWrapper(object.clone(), itemStatus, context); - } catch (Exception ex) { - result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); - showResult(result, false); - throw new RestartResponseException(getRestartResponsePage()); - } - - showResult(result, false); - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Loaded focus wrapper:\n{}", wrapper.debugDump()); - } - - return wrapper; - } - - protected Collection> buildGetOptions() { - return getOperationOptionsBuilder() - .item(UserType.F_JPEG_PHOTO).retrieve() - .build(); - } - -// private void loadParentOrgs(PrismObjectWrapper wrapper, Task task, OperationResult result) { -// OperationResult subResult = result.createMinorSubresult(OPERATION_LOAD_PARENT_ORGS); -// PrismObject focus = wrapper.getObject(); -// // Load parent organizations (full objects). There are used in the -// // summary panel and also in the main form. -// // Do it here explicitly instead of using resolve option to have ability -// // to better handle (ignore) errors. -// for (ObjectReferenceType parentOrgRef : focus.asObjectable().getParentOrgRef()) { -// -// PrismObject parentOrg = null; -// try { -// -// parentOrg = getModelService().getObject(OrgType.class, parentOrgRef.getOid(), null, task, -// subResult); -// LOGGER.trace("Loaded parent org with result {}", -// new Object[] { subResult.getLastSubresult() }); -// } catch (AuthorizationException e) { -// // This can happen if the user has permission to read parentOrgRef but it does not have -// // the permission to read target org -// // It is OK to just ignore it. -// subResult.muteLastSubresultError(); -// LOGGER.debug("User {} does not have permission to read parent org unit {} (ignoring error)", task.getOwner().getName(), parentOrgRef.getOid()); -// } catch (Exception ex) { -// subResult.recordWarning(createStringResource("PageAdminObjectDetails.message.loadParentOrgs.warning", parentOrgRef.getOid()).getString(), ex); -// LOGGER.warn("Cannot load parent org {}: {}", parentOrgRef.getOid(), ex.getMessage(), ex); -// } -// -// if (parentOrg != null) { -// wrapper.getParentOrgs().add(parentOrg); -// } -// } -// subResult.computeStatus(); -// } - - protected abstract Class getRestartResponsePage(); - - public Object findParam(String param, String oid, OperationResult result) { - - Object object = null; - - for (OperationResult subResult : result.getSubresults()) { - if (subResult != null && subResult.getParams() != null) { - if (subResult.getParams().get(param) != null - && subResult.getParams().get(OperationResult.PARAM_OID) != null - && subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) { - return subResult.getParams().get(param); - } - object = findParam(param, oid, subResult); - - } - } - return object; - } - - // TODO put this into correct place - protected boolean previewRequested; - - /** - * This will be called from the main form when save button is pressed. - */ - public void savePerformed(AjaxRequestTarget target) { - progressPanel.onBeforeSave(); - OperationResult result = new OperationResult(OPERATION_SAVE); - previewRequested = false; - saveOrPreviewPerformed(target, result, false); - } - - public void previewPerformed(AjaxRequestTarget target) { - progressPanel.onBeforeSave(); - OperationResult result = new OperationResult(OPERATION_PREVIEW_CHANGES); - previewRequested = true; - saveOrPreviewPerformed(target, result, true); - } - - public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly) { - saveOrPreviewPerformed(target, result, previewOnly, null); - } - - public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly, Task task) { - boolean delegationChangesExist = processDeputyAssignments(previewOnly); - - PrismObjectWrapper objectWrapper = getObjectWrapper(); - LOGGER.debug("Saving object {}", objectWrapper); - - // todo: improve, delta variable is quickfix for MID-1006 - // redirecting to user list page everytime user is created in repository - // during user add in gui, - // and we're not taking care about account/assignment create errors - // (error message is still displayed) - delta = null; - - if(task == null) { - task = createSimpleTask(OPERATION_SEND_TO_SUBMIT); - } - - ModelExecuteOptions options = getOptions(previewOnly); - - LOGGER.debug("Using execute options {}.", options); - - try { - reviveModels(); - - delta = objectWrapper.getObjectDelta(); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("User delta computed from form:\n{}", new Object[] { delta.debugDump(3) }); - } - } catch (Exception ex) { - result.recordFatalError(getString("pageAdminObjectDetails.message.cantCreateObject"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Create Object failed", ex); - showResult(result); - target.add(getFeedbackPanel()); - return; - } - - switch (objectWrapper.getStatus()) { - case ADDED: - try { - PrismObject objectToAdd = delta.getObjectToAdd(); - WebComponentUtil.encryptCredentials(objectToAdd, true, getMidpointApplication()); - prepareObjectForAdd(objectToAdd); - getPrismContext().adopt(objectToAdd, getCompileTimeClass()); - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Delta before add user:\n{}", new Object[] { delta.debugDump(3) }); - } - - if (!delta.isEmpty()) { - delta.revive(getPrismContext()); - - final Collection> deltas = WebComponentUtil.createDeltaCollection(delta); - final Collection validationErrors = performCustomValidation(objectToAdd, deltas); - if (checkValidationErrors(target, validationErrors)) { - return; - } - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else { - result.recordSuccess(); - } - } catch (Exception ex) { - result.recordFatalError(getString("pageFocus.message.cantCreateFocus"), ex); - LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex); - showResult(result); - } - break; - - case NOT_CHANGED: - try { - WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); - prepareObjectDeltaForModify(delta); //preparing of deltas for projections (ADD, DELETE, UNLINK) - - if (LOGGER.isTraceEnabled()) { - LOGGER.trace("Delta before modify user:\n{}", new Object[] { delta.debugDump(3) }); - } - - Collection> deltas = new ArrayList<>(); - if (!delta.isEmpty()) { - delta.revive(getPrismContext()); - deltas.add(delta); - } - - List> additionalDeltas = getAdditionalModifyDeltas(result); - if (additionalDeltas != null) { - for (ObjectDelta additionalDelta : additionalDeltas) { - if (!additionalDelta.isEmpty()) { - additionalDelta.revive(getPrismContext()); - deltas.add(additionalDelta); - } - } - } - - if (delta.isEmpty() && ModelExecuteOptions.isReconcile(options)) { - ObjectDelta emptyDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), - objectWrapper.getObject().getOid()); - deltas.add(emptyDelta); - - Collection validationErrors = performCustomValidation(null, deltas); - if (checkValidationErrors(target, validationErrors)) { - return; - } - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else if (!deltas.isEmpty()) { - Collection validationErrors = performCustomValidation(null, deltas); - if (checkValidationErrors(target, validationErrors)) { - return; - } - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else if (previewOnly && delta.isEmpty() && delegationChangesExist){ - if (isSaveInBackground()){ - progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); - } else { - progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); - } - } else { - progressPanel.clearProgressPanel(); // from previous attempts (useful only if we would call finishProcessing at the end, but that's not the case now) - if (!previewOnly) { - if (!delegationChangesExist) { - result.recordWarning(getString("PageAdminObjectDetails.noChangesSave")); - showResult(result); - } - redirectBack(); - } else { - if (!delegationChangesExist) { - warn(getString("PageAdminObjectDetails.noChangesPreview")); - target.add(getFeedbackPanel()); - } - } - } - - } catch (Exception ex) { - if (!executeForceDelete(objectWrapper, task, options, result)) { - result.recordFatalError(getString("pageUser.message.cantUpdateUser"), ex); - LoggingUtils.logUnexpectedException(LOGGER, getString("pageUser.message.cantUpdateUser"), ex); - } else { - result.recomputeStatus(); - } - showResult(result); - } - break; - // support for add/delete containers (e.g. delete credentials) - default: - error(getString("pageAdminFocus.message.unsupportedState", objectWrapper.getStatus())); - } - -// result.recomputeStatus(); -// -// if (!result.isInProgress()) { -// LOGGER.trace("Result NOT in progress, calling finishProcessing"); -// finishProcessing(target, result, false); -// } - - LOGGER.trace("returning from saveOrPreviewPerformed"); - } - - protected boolean processDeputyAssignments(boolean previewOnly){ - return false; - } - - protected boolean checkValidationErrors(AjaxRequestTarget target, Collection validationErrors) { - if (validationErrors != null && !validationErrors.isEmpty()) { - for (SimpleValidationError error : validationErrors) { - LOGGER.error("Validation error, attribute: '" + error.printAttribute() - + "', message: '" + error.getMessage() + "'."); - error("Validation error, attribute: '" + error.printAttribute() - + "', message: '" + error.getMessage() + "'."); - } - - target.add(getFeedbackPanel()); - return true; - } - return false; - } - - @Override - public void startProcessing(AjaxRequestTarget target, OperationResult result) { - LOGGER.trace("startProcessing called, making main panel invisible"); - mainPanel.setVisible(false); - target.add(mainPanel); - } - - @NotNull - protected ModelExecuteOptions getOptions(boolean previewOnly) { - ModelExecuteOptions options = mainPanel.getExecuteChangeOptionsDto().createOptions(); - if (previewOnly) { - options.getOrCreatePartialProcessing().setApprovals(PartialProcessingTypeType.PROCESS); - } - return options; - } - - protected void prepareObjectForAdd(PrismObject object) throws SchemaException { - - } - - protected void prepareObjectDeltaForModify(ObjectDelta objectDelta) throws SchemaException { - - } - - protected List> getAdditionalModifyDeltas(OperationResult result) { - return null; - } - - protected boolean executeForceDelete(PrismObjectWrapper userWrapper, Task task, ModelExecuteOptions options, - OperationResult parentResult) { - return isForce(); - } - - protected boolean isForce() { - return getMainPanel().getExecuteChangeOptionsDto().isForce(); - } - - protected boolean isKeepDisplayingResults() { - return getMainPanel().getExecuteChangeOptionsDto().isKeepDisplayingResults(); - } - - protected boolean isSaveInBackground(){ - return getMainPanel().getExecuteChangeOptionsDto().isSaveInBackground(); - } - - protected Collection performCustomValidation(PrismObject object, - Collection> deltas) throws SchemaException { - Collection errors = null; - - if (object == null) { - if (getObjectWrapper() != null && getObjectWrapper().getObjectOld() != null) { - object = getObjectWrapper().getObjectOld().clone(); // otherwise original object could get corrupted e.g. by applying the delta below - - for (ObjectDelta delta : deltas) { - // because among deltas there can be also ShadowType deltas - if (UserType.class.isAssignableFrom(delta.getObjectTypeClass())) { - delta.applyTo(object); - } - } - } - } else { - object = object.clone(); - } - - performAdditionalValidation(object, deltas, errors); - - for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) { - if (errors == null) { - errors = validator.validateObject(object, deltas); - } else { - errors.addAll(validator.validateObject(object, deltas)); - } - } - - return errors; - } - - protected void performAdditionalValidation(PrismObject object, - Collection> deltas, Collection errors) throws SchemaException { - - } - - public List getObjectFormTypes() { - Task task = createSimpleTask(OPERATION_LOAD_GUI_CONFIGURATION); - OperationResult result = task.getResult(); - CompiledGuiProfile adminGuiConfiguration; - try { - adminGuiConfiguration = getModelInteractionService().getCompiledGuiProfile(task, result); - } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { - throw new SystemException("Cannot load GUI configuration: "+e.getMessage(), e); - } - ObjectFormsType objectFormsType = adminGuiConfiguration.getObjectForms(); - if (objectFormsType == null) { - return null; - } - List objectForms = objectFormsType.getObjectForm(); - if (objectForms == null || objectForms.isEmpty()) { - return objectForms; - } - List validObjectForms = new ArrayList<>(); - for (ObjectFormType objectForm: objectForms) { - if (isSupportedObjectType(objectForm.getType())) { - validObjectForms.add(objectForm); - } - } - return validObjectForms; - } - - protected boolean isSupportedObjectType(QName type) { - ObjectTypes objectType = ObjectTypes.getObjectType(getCompileTimeClass()); - return QNameUtil.match(objectType.getTypeQName(),type); - } - - public void setSaveOnConfigure(boolean saveOnConfigure) { - this.saveOnConfigure = saveOnConfigure; - } - - public boolean isSaveOnConfigure() { - return saveOnConfigure; - } - - public boolean isForcedPreview() { - GuiObjectDetailsPageType objectDetails = getCompiledGuiProfile().findObjectDetailsConfiguration(getCompileTimeClass()); - return objectDetails != null && DetailsPageSaveMethodType.FORCED_PREVIEW.equals(objectDetails.getSaveMethod()); - } - -} +/* + * Copyright (c) 2010-2018 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.web.page.admin; + +import java.util.*; + +import javax.xml.namespace.QName; + +import com.evolveum.midpoint.gui.api.component.*; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.util.WebPrismUtil; +import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; +import com.evolveum.midpoint.model.api.context.ModelContext; +import com.evolveum.midpoint.prism.PrismContainerValue; +import com.evolveum.midpoint.prism.query.ObjectFilter; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.web.component.prism.show.PagePreviewChanges; +import com.evolveum.midpoint.web.component.util.SelectableBean; +import com.evolveum.midpoint.web.component.util.VisibleBehaviour; +import com.evolveum.midpoint.web.page.admin.configuration.PageSystemConfiguration; +import com.evolveum.midpoint.web.page.admin.server.OperationalButtonsPanel; +import com.evolveum.midpoint.web.security.util.SecurityUtils; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.Page; +import org.apache.wicket.RestartResponseException; +import org.apache.wicket.Session; +import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.behavior.Behavior; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.protocol.http.WebSession; +import org.apache.wicket.request.mapper.parameter.PageParameters; +import org.apache.wicket.util.string.StringValue; +import org.apache.wicket.util.time.Duration; +import org.jetbrains.annotations.NotNull; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; +import com.evolveum.midpoint.gui.impl.factory.WrapperContext; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.ObjectTypes; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.ObjectSummaryPanel; +import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; +import com.evolveum.midpoint.web.component.progress.ProgressPanel; +import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.page.admin.users.dto.FocusSubwrapperDto; +import com.evolveum.midpoint.web.util.OnePageParameterEncoder; +import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; +import com.evolveum.midpoint.web.util.validation.SimpleValidationError; + +/** + * @author semancik + */ +public abstract class PageAdminObjectDetails extends PageAdmin + implements ProgressReportingAwarePage { + private static final long serialVersionUID = 1L; + + private static final String DOT_CLASS = PageAdminObjectDetails.class.getName() + "."; + + public static final String PARAM_RETURN_PAGE = "returnPage"; + + private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; + private static final String OPERATION_LOAD_PARENT_ORGS = DOT_CLASS + "loadParentOrgs"; + private static final String OPERATION_LOAD_GUI_CONFIGURATION = DOT_CLASS + "loadGuiConfiguration"; + protected static final String OPERATION_SAVE = DOT_CLASS + "save"; + protected static final String OPERATION_PREVIEW_CHANGES = DOT_CLASS + "previewChanges"; + protected static final String OPERATION_SEND_TO_SUBMIT = DOT_CLASS + "sendToSubmit"; + protected static final String OPERATION_LOAD_ARCHETYPE_REF = DOT_CLASS + "loadArchetypeRef"; + protected static final String OPERATION_EXECUTE_CHANGES = DOT_CLASS + "executeChangesTask"; + protected static final String OPERATION_EXECUTE_ARCHETYPE_CHANGES = DOT_CLASS + "executeArchetypeChanges"; + protected static final String OPERATION_LOAD_FILTERED_ARCHETYPES = DOT_CLASS + "loadFilteredArchetypes"; + + protected static final String ID_SUMMARY_PANEL = "summaryPanel"; + protected static final String ID_MAIN_PANEL = "mainPanel"; + private static final String ID_PROGRESS_PANEL = "progressPanel"; + private static final String ID_BUTTONS = "buttons"; + + private static final Trace LOGGER = TraceManager.getTrace(PageAdminObjectDetails.class); + + private LoadableModel> objectModel; + private LoadableModel>> parentOrgModel; + + private ProgressPanel progressPanel; + + // used to determine whether to leave this page or stay on it (after + // operation finishing) + private ObjectDelta delta; + + private AbstractObjectMainPanel mainPanel; + private boolean saveOnConfigure; // ugly hack - whether to invoke 'Save' when returning to this page + + private boolean editingFocus = false; //before we got isOidParameterExists status depending only on oid parameter existence + //we should set editingFocus=true not only when oid parameter exists but also + //when object is given as a constructor parameter + + public boolean isEditingFocus() { + return editingFocus; + } + + @Override + protected void createBreadcrumb() { + createInstanceBreadcrumb(); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + if (saveOnConfigure) { + saveOnConfigure = false; + add(new AbstractAjaxTimerBehavior(Duration.milliseconds(100)) { + @Override + protected void onTimer(AjaxRequestTarget target) { + stop(target); + savePerformed(target); + } + }); + } + } + + @Override + protected IModel createPageTitleModel() { + if (PageAdminObjectDetails.this instanceof PageSystemConfiguration){ + return super.createPageTitleModel(); + } + String simpleName = getObjectSimpleName(); + String lokalizedSimpleName = new StringResourceModel("ObjectType." + simpleName).setDefaultValue(simpleName).getString(); + if (isAdd()) { + return createStringResource("PageAdminObjectDetails.title.new", lokalizedSimpleName); + } + + String name = null; + if (getObjectWrapper() != null && getObjectWrapper().getObject() != null) { + name = WebComponentUtil.getName(getObjectWrapper().getObject()); + } + + return createStringResource("PageAdminObjectDetails.title.edit.readonly.${readOnly}", getObjectModel(), lokalizedSimpleName, name); + } + + private String getObjectSimpleName(){ + if (getObjectWrapper() != null && getObjectWrapper().getObject() != null + && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType){ + AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); + DisplayType displayType = WebComponentUtil + .getArchetypePolicyDisplayType(assignmentHolderObj, PageAdminObjectDetails.this); + if (displayType == null){ + ObjectReferenceType archetypeReference = getObjectArchetypeRef(); + if (archetypeReference != null){ + OperationResult result = new OperationResult(OPERATION_LOAD_ARCHETYPE_REF); + Task task = createSimpleTask(OPERATION_LOAD_ARCHETYPE_REF); + PrismObject archetypeObj = WebModelServiceUtils.resolveReferenceNoFetch(archetypeReference, + this, task, result); + displayType = archetypeObj != null && archetypeObj.asObjectable().getArchetypePolicy() != null ? + archetypeObj.asObjectable().getArchetypePolicy().getDisplay() : null; + } + } + if (displayType != null && displayType.getLabel() != null) { + String archetypeLocalizedName = getLocalizationService() + .translate(displayType.getLabel().toPolyString(), WebComponentUtil.getCurrentLocale(), true); + if (StringUtils.isNotEmpty(archetypeLocalizedName)) { + return archetypeLocalizedName; + } + } + } + return getCompileTimeClass().getSimpleName(); + } + + public boolean isAdd() { + return !isOidParameterExists() && !editingFocus; + } + + public LoadableModel> getObjectModel() { + return objectModel; + } + + protected AbstractObjectMainPanel getMainPanel() { + return mainPanel; + } + + public PrismObjectWrapper getObjectWrapper() { + return objectModel.getObject(); + } + + public List> getParentOrgs() { + return parentOrgModel.getObject(); + } + + public ObjectDelta getDelta() { + return delta; + } + + public void setDelta(ObjectDelta delta) { + this.delta = delta; + } + + public ProgressPanel getProgressPanel() { + return progressPanel; + } + + protected void reviveModels() throws SchemaException { + WebComponentUtil.revive(objectModel, getPrismContext()); + WebComponentUtil.revive(parentOrgModel, getPrismContext()); + } + + public abstract Class getCompileTimeClass(); + + + public void initialize(final PrismObject objectToEdit) { + boolean isNewObject = objectToEdit == null && StringUtils.isEmpty(getObjectOidParameter()); + + initialize(objectToEdit, isNewObject, false); + } + + public void initialize(final PrismObject objectToEdit, boolean isNewObject) { + initialize(objectToEdit, isNewObject, false); + } + + public void initialize(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { + initializeModel(objectToEdit, isNewObject, isReadonly); +// initLayout(); + } + + protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { + editingFocus = !isNewObject; + + objectModel = new LoadableModel>(false) { + private static final long serialVersionUID = 1L; + + @Override + protected PrismObjectWrapper load() { + PrismObjectWrapper wrapper = loadObjectWrapper(objectToEdit, isReadonly); +// wrapper.sort(); + return wrapper; + } + }; + + parentOrgModel = new LoadableModel>>(false) { + private static final long serialVersionUID = 1L; + + @Override + protected List> load() { + return loadOrgWrappers(); + } + }; + } + + private ObjectReferenceType getObjectArchetypeRef() { + ObjectReferenceType archetypeReference = null; + if (getObjectWrapper() != null && getObjectWrapper().getObject() != null + && getObjectWrapper().getObject().asObjectable() instanceof AssignmentHolderType) { + AssignmentHolderType assignmentHolderObj = (AssignmentHolderType) getObjectWrapper().getObject().asObjectable(); + if (assignmentHolderObj.getAssignment() != null) { + for (AssignmentType assignment : assignmentHolderObj.getAssignment()) { + if (assignment.getTargetRef() != null && assignment.getTargetRef().getType() != null + && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { + archetypeReference = assignment.getTargetRef(); + break; + } + } + } + } + return archetypeReference; + } + + protected List> loadOrgWrappers() { + // WRONG!! TODO: fix + return null; + } + + protected abstract O createNewObject(); + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + protected void initLayout() { + initLayoutSummaryPanel(); + initOperationalButtonsPanel(); + + mainPanel = createMainPanel(ID_MAIN_PANEL); + mainPanel.setOutputMarkupId(true); + add(mainPanel); + + progressPanel = new ProgressPanel(ID_PROGRESS_PANEL); + add(progressPanel); + } + + protected abstract ObjectSummaryPanel createSummaryPanel(); + + protected void initLayoutSummaryPanel() { + + ObjectSummaryPanel summaryPanel = createSummaryPanel(); + summaryPanel.setOutputMarkupId(true); + + setSummaryPanelVisibility(summaryPanel); + add(summaryPanel); + } + + protected void setSummaryPanelVisibility(ObjectSummaryPanel summaryPanel){ + summaryPanel.add(new VisibleEnableBehaviour() { + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return isOidParameterExists() || editingFocus; + } + }); + } + + private void initOperationalButtonsPanel(){ + OperationalButtonsPanel opButtonPanel = new OperationalButtonsPanel(ID_BUTTONS) { + private static final long serialVersionUID = 1L; + + @Override + protected void addButtons(RepeatingView repeatingView) { + initOperationalButtons(repeatingView); + } + }; + if (getAdditionalOperationalButtonPanelBehaviors() != null && !getAdditionalOperationalButtonPanelBehaviors().isEmpty()){ + getAdditionalOperationalButtonPanelBehaviors().forEach(this::add); + } + opButtonPanel.setOutputMarkupId(true); + opButtonPanel.add(new VisibleBehaviour(() -> isEditingFocus() && opButtonPanel.buttonsExist())); + add(opButtonPanel); + } + + protected List getAdditionalOperationalButtonPanelBehaviors(){ + return new ArrayList<>(); + } + + protected void initOperationalButtons(RepeatingView repeatingView){ + if (getObjectArchetypeRef() != null) { + AjaxButton changeArchetype = new AjaxButton(repeatingView.newChildId(), createStringResource("PageAdminObjectDetails.button.changeArchetype")) { + @Override + public void onClick(AjaxRequestTarget target) { + changeArchetypeButtonClicked(target); + } + }; + changeArchetype.add(new VisibleBehaviour(() -> getObjectArchetypeRef() != null)); + changeArchetype.add(AttributeAppender.append("class", "btn-default")); + repeatingView.add(changeArchetype); + } + } + + protected OperationalButtonsPanel getOperationalButtonsPanel(){ + return (OperationalButtonsPanel) get(ID_BUTTONS); + } + + private void changeArchetypeButtonClicked(AjaxRequestTarget target){ + + AssignmentPopup changeArchetypePopup = new AssignmentPopup(getMainPopupBodyId()) { + + private static final long serialVersionUID = 1L; + + @Override + protected void addPerformed(AjaxRequestTarget target, List newAssignmentsList) { + super.addPerformed(target, newAssignmentsList); + try { + PrismContainerWrapper assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); + ((List) newAssignmentsList).forEach(assignment -> { + PrismContainerValue newAssignment = assignmentsWrapper.getItem().createNewValue(); + assignmentsWrapper.getValues().forEach(assignmentValue -> { + if (assignmentValue.getRealValue().getTargetRef() != null + && assignmentValue.getRealValue().getTargetRef().getType() != null + && QNameUtil.match(assignmentValue.getRealValue().getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)){ + assignmentValue.setStatus(ValueStatus.DELETED); + } + }); + AssignmentType assignmentType = newAssignment.asContainerable(); + assignmentType.setTargetRef(assignment.getTargetRef()); + WebPrismUtil.createNewValueWrapper(assignmentsWrapper, newAssignment, PageAdminObjectDetails.this, target); + OperationResult result = new OperationResult(OPERATION_EXECUTE_ARCHETYPE_CHANGES); + Task task = createSimpleTask(OPERATION_EXECUTE_ARCHETYPE_CHANGES); + try { + ObjectDelta archetypeDelta = getObjectWrapper().getObjectDelta(); + if (!archetypeDelta.isEmpty()) { + archetypeDelta.revive(getPrismContext()); + getModelService().executeChanges(WebComponentUtil.createDeltaCollection(archetypeDelta), null, task, result); + result.computeStatus(); + } + } catch (Exception e) { + LOGGER.error("Cannot save archetype assignment changes: {}", e.getMessage()); + } + showResult(result); + }); + } catch (SchemaException e) { + LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); + } + target.add(PageAdminObjectDetails.this.getFeedbackPanel()); + } + + @Override + protected List createAssignmentTabs() { + List tabs = new ArrayList<>(); + + tabs.add(new PanelTab(getPageBase().createStringResource("ObjectTypes.ARCHETYPE"), + new VisibleBehaviour(() -> true)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusTypeAssignmentPopupTabPanel(panelId, ObjectTypes.ARCHETYPE) { + private static final long serialVersionUID = 1L; + + @Override + protected PrismContainerWrapper getAssignmentWrapperModel() { + PrismContainerWrapper assignmentsWrapper = null; + try { + assignmentsWrapper = getObjectWrapper().findContainer(FocusType.F_ASSIGNMENT); + } catch (SchemaException e) { + LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); + } + return assignmentsWrapper; + } + + @Override + protected List getSupportedRelations() { + return Collections.singletonList(SchemaConstants.ORG_DEFAULT); + } + + @Override + protected void onSelectionPerformed(AjaxRequestTarget target, IModel> rowModel) { + target.add(getObjectListPanel()); + tabLabelPanelUpdate(target); + } + + @Override + protected IModel getObjectSelectCheckBoxEnableModel(IModel> rowModel){ + if (rowModel == null){ + return Model.of(false); + } + List selectedObjects = getSelectedObjectsList(); + return Model.of(selectedObjects == null || selectedObjects.size() == 0 + || (rowModel.getObject() != null && rowModel.getObject().isSelected())); + } + + + @Override + protected ObjectTypes getObjectType() { + return ObjectTypes.ARCHETYPE; + } + + @Override + protected ObjectQuery addFilterToContentQuery(ObjectQuery query){ + super.addFilterToContentQuery(query); + if (query == null) { + query = getPrismContext().queryFactory().createQuery(); + } + List archetypeOidsList = getFilteredArchetypeOidsList(); + ObjectFilter filter = getPrismContext().queryFor(ArchetypeType.class) + .id(archetypeOidsList.toArray(new String[0])) + .buildFilter(); + query.addFilter(filter); + return query; + } + }; + } + }); + return tabs; + } + }; + + changeArchetypePopup.setOutputMarkupPlaceholderTag(true); + showMainPopup(changeArchetypePopup, target); + + } + + private List getFilteredArchetypeOidsList(){ + OperationResult result = new OperationResult(OPERATION_LOAD_FILTERED_ARCHETYPES); + PrismObject obj = getObjectWrapper().getObject(); + List oidsList = new ArrayList<>(); + try { + List filteredArchetypes = getModelInteractionService().getFilteredArchetypesByHolderType(obj, result); + if (filteredArchetypes != null){ + filteredArchetypes.forEach(archetype -> oidsList.add(archetype.getOid())); + } + } catch (SchemaException ex){ + result.recordPartialError(ex.getLocalizedMessage()); + LOGGER.error("Couldn't load assignment target specification for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); + } + return oidsList; + } + + protected abstract AbstractObjectMainPanel createMainPanel(String id); + + protected String getObjectOidParameter() { + PageParameters parameters = getPageParameters(); + LOGGER.trace("Page parameters: {}", parameters); + StringValue oidValue = parameters.get(OnePageParameterEncoder.PARAMETER); + LOGGER.trace("OID parameter: {}", oidValue); + if (oidValue == null) { + return null; + } + String oid = oidValue.toString(); + if (StringUtils.isBlank(oid)) { + return null; + } + return oid; + } + + protected ObjectSummaryPanel getSummaryPanel() { + return (ObjectSummaryPanel) get(ID_SUMMARY_PANEL); + } + + public boolean isOidParameterExists() { + return getObjectOidParameter() != null; + } + + protected PrismObjectWrapper loadObjectWrapper(PrismObject objectToEdit, boolean isReadonly) { + Task task = createSimpleTask(OPERATION_LOAD_OBJECT); + OperationResult result = task.getResult(); + PrismObject object = null; + try { + if (!isOidParameterExists()) { + if (objectToEdit == null) { + LOGGER.trace("Loading object: New object (creating)"); + O focusType = createNewObject(); + + // Apply subtype using page parameters + List subtypes = getPageParameters().getValues(ObjectType.F_SUBTYPE.getLocalPart()); + subtypes.stream().filter(p -> !p.isEmpty()).forEach(c -> focusType.subtype(c.toString())); + + getMidpointApplication().getPrismContext().adopt(focusType); + object = (PrismObject) focusType.asPrismObject(); + } else { + LOGGER.trace("Loading object: New object (supplied): {}", objectToEdit); + object = objectToEdit; + } + } else { + + String focusOid = getObjectOidParameter(); + object = WebModelServiceUtils.loadObject(getCompileTimeClass(), focusOid, buildGetOptions(), this, task, result); + LOGGER.trace("Loading object: Existing object (loadled): {} -> {}", focusOid, object); + } + + result.recordSuccess(); + } catch (Exception ex) { + result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + } + + showResult(result, false); + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Loaded object:\n{}", object.debugDump()); + } + + if (object == null) { + if (isOidParameterExists()) { + getSession().error(getString("pageAdminFocus.message.cantEditFocus")); + } else { + getSession().error(getString("pageAdminFocus.message.cantNewFocus")); + } + throw new RestartResponseException(getRestartResponsePage()); + } + + ItemStatus itemStatus = isOidParameterExists() || editingFocus ? ItemStatus.NOT_CHANGED : ItemStatus.ADDED; + PrismObjectWrapper wrapper; + + PrismObjectWrapperFactory factory = getRegistry().getObjectWrapperFactory(object.getDefinition()); + WrapperContext context = new WrapperContext(task, result); + context.setCreateIfEmpty(ItemStatus.ADDED == itemStatus); + //we don't want to set to false.. refactor this method to take either enum (READONLY, AUTO, ...) or + // Boolean instead of boolean isReadonly + if (isReadonly) { + context.setReadOnly(isReadonly); + } + + + try { + wrapper = factory.createObjectWrapper(object.clone(), itemStatus, context); + } catch (Exception ex) { + result.recordFatalError(getString("PageAdminObjectDetails.message.loadObjectWrapper.fatalError"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load object", ex); + showResult(result, false); + throw new RestartResponseException(getRestartResponsePage()); + } + + showResult(result, false); + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Loaded focus wrapper:\n{}", wrapper.debugDump()); + } + + return wrapper; + } + + protected Collection> buildGetOptions() { + return getOperationOptionsBuilder() + .item(UserType.F_JPEG_PHOTO).retrieve() + .build(); + } + +// private void loadParentOrgs(PrismObjectWrapper wrapper, Task task, OperationResult result) { +// OperationResult subResult = result.createMinorSubresult(OPERATION_LOAD_PARENT_ORGS); +// PrismObject focus = wrapper.getObject(); +// // Load parent organizations (full objects). There are used in the +// // summary panel and also in the main form. +// // Do it here explicitly instead of using resolve option to have ability +// // to better handle (ignore) errors. +// for (ObjectReferenceType parentOrgRef : focus.asObjectable().getParentOrgRef()) { +// +// PrismObject parentOrg = null; +// try { +// +// parentOrg = getModelService().getObject(OrgType.class, parentOrgRef.getOid(), null, task, +// subResult); +// LOGGER.trace("Loaded parent org with result {}", +// new Object[] { subResult.getLastSubresult() }); +// } catch (AuthorizationException e) { +// // This can happen if the user has permission to read parentOrgRef but it does not have +// // the permission to read target org +// // It is OK to just ignore it. +// subResult.muteLastSubresultError(); +// LOGGER.debug("User {} does not have permission to read parent org unit {} (ignoring error)", task.getOwner().getName(), parentOrgRef.getOid()); +// } catch (Exception ex) { +// subResult.recordWarning(createStringResource("PageAdminObjectDetails.message.loadParentOrgs.warning", parentOrgRef.getOid()).getString(), ex); +// LOGGER.warn("Cannot load parent org {}: {}", parentOrgRef.getOid(), ex.getMessage(), ex); +// } +// +// if (parentOrg != null) { +// wrapper.getParentOrgs().add(parentOrg); +// } +// } +// subResult.computeStatus(); +// } + + protected abstract Class getRestartResponsePage(); + + public Object findParam(String param, String oid, OperationResult result) { + + Object object = null; + + for (OperationResult subResult : result.getSubresults()) { + if (subResult != null && subResult.getParams() != null) { + if (subResult.getParams().get(param) != null + && subResult.getParams().get(OperationResult.PARAM_OID) != null + && subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) { + return subResult.getParams().get(param); + } + object = findParam(param, oid, subResult); + + } + } + return object; + } + + // TODO put this into correct place + protected boolean previewRequested; + + /** + * This will be called from the main form when save button is pressed. + */ + public void savePerformed(AjaxRequestTarget target) { + progressPanel.onBeforeSave(); + OperationResult result = new OperationResult(OPERATION_SAVE); + previewRequested = false; + saveOrPreviewPerformed(target, result, false); + } + + public void previewPerformed(AjaxRequestTarget target) { + progressPanel.onBeforeSave(); + OperationResult result = new OperationResult(OPERATION_PREVIEW_CHANGES); + previewRequested = true; + saveOrPreviewPerformed(target, result, true); + } + + public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly) { + saveOrPreviewPerformed(target, result, previewOnly, null); + } + + public void saveOrPreviewPerformed(AjaxRequestTarget target, OperationResult result, boolean previewOnly, Task task) { + boolean delegationChangesExist = processDeputyAssignments(previewOnly); + + PrismObjectWrapper objectWrapper = getObjectWrapper(); + LOGGER.debug("Saving object {}", objectWrapper); + + // todo: improve, delta variable is quickfix for MID-1006 + // redirecting to user list page everytime user is created in repository + // during user add in gui, + // and we're not taking care about account/assignment create errors + // (error message is still displayed) + delta = null; + + if(task == null) { + task = createSimpleTask(OPERATION_SEND_TO_SUBMIT); + } + + ModelExecuteOptions options = getOptions(previewOnly); + + LOGGER.debug("Using execute options {}.", options); + + try { + reviveModels(); + + delta = objectWrapper.getObjectDelta(); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("User delta computed from form:\n{}", new Object[] { delta.debugDump(3) }); + } + } catch (Exception ex) { + result.recordFatalError(getString("pageAdminObjectDetails.message.cantCreateObject"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Create Object failed", ex); + showResult(result); + target.add(getFeedbackPanel()); + return; + } + + switch (objectWrapper.getStatus()) { + case ADDED: + try { + PrismObject objectToAdd = delta.getObjectToAdd(); + WebComponentUtil.encryptCredentials(objectToAdd, true, getMidpointApplication()); + prepareObjectForAdd(objectToAdd); + getPrismContext().adopt(objectToAdd, getCompileTimeClass()); + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Delta before add user:\n{}", new Object[] { delta.debugDump(3) }); + } + + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + + final Collection> deltas = WebComponentUtil.createDeltaCollection(delta); + final Collection validationErrors = performCustomValidation(objectToAdd, deltas); + if (checkValidationErrors(target, validationErrors)) { + return; + } + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else { + result.recordSuccess(); + } + } catch (Exception ex) { + result.recordFatalError(getString("pageFocus.message.cantCreateFocus"), ex); + LoggingUtils.logUnexpectedException(LOGGER, "Create user failed", ex); + showResult(result); + } + break; + + case NOT_CHANGED: + try { + WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); + prepareObjectDeltaForModify(delta); //preparing of deltas for projections (ADD, DELETE, UNLINK) + + if (LOGGER.isTraceEnabled()) { + LOGGER.trace("Delta before modify user:\n{}", new Object[] { delta.debugDump(3) }); + } + + Collection> deltas = new ArrayList<>(); + if (!delta.isEmpty()) { + delta.revive(getPrismContext()); + deltas.add(delta); + } + + List> additionalDeltas = getAdditionalModifyDeltas(result); + if (additionalDeltas != null) { + for (ObjectDelta additionalDelta : additionalDeltas) { + if (!additionalDelta.isEmpty()) { + additionalDelta.revive(getPrismContext()); + deltas.add(additionalDelta); + } + } + } + + if (delta.isEmpty() && ModelExecuteOptions.isReconcile(options)) { + ObjectDelta emptyDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), + objectWrapper.getObject().getOid()); + deltas.add(emptyDelta); + + Collection validationErrors = performCustomValidation(null, deltas); + if (checkValidationErrors(target, validationErrors)) { + return; + } + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else if (!deltas.isEmpty()) { + Collection validationErrors = performCustomValidation(null, deltas); + if (checkValidationErrors(target, validationErrors)) { + return; + } + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else if (previewOnly && delta.isEmpty() && delegationChangesExist){ + if (isSaveInBackground()){ + progressPanel.executeChangesInBackground(deltas, previewOnly, options, task, result, target); + } else { + progressPanel.executeChanges(deltas, previewOnly, options, task, result, target); + } + } else { + progressPanel.clearProgressPanel(); // from previous attempts (useful only if we would call finishProcessing at the end, but that's not the case now) + if (!previewOnly) { + if (!delegationChangesExist) { + result.recordWarning(getString("PageAdminObjectDetails.noChangesSave")); + showResult(result); + } + redirectBack(); + } else { + if (!delegationChangesExist) { + warn(getString("PageAdminObjectDetails.noChangesPreview")); + target.add(getFeedbackPanel()); + } + } + } + + } catch (Exception ex) { + if (!executeForceDelete(objectWrapper, task, options, result)) { + result.recordFatalError(getString("pageUser.message.cantUpdateUser"), ex); + LoggingUtils.logUnexpectedException(LOGGER, getString("pageUser.message.cantUpdateUser"), ex); + } else { + result.recomputeStatus(); + } + showResult(result); + } + break; + // support for add/delete containers (e.g. delete credentials) + default: + error(getString("pageAdminFocus.message.unsupportedState", objectWrapper.getStatus())); + } + +// result.recomputeStatus(); +// +// if (!result.isInProgress()) { +// LOGGER.trace("Result NOT in progress, calling finishProcessing"); +// finishProcessing(target, result, false); +// } + + LOGGER.trace("returning from saveOrPreviewPerformed"); + } + + protected boolean processDeputyAssignments(boolean previewOnly){ + return false; + } + + protected boolean checkValidationErrors(AjaxRequestTarget target, Collection validationErrors) { + if (validationErrors != null && !validationErrors.isEmpty()) { + for (SimpleValidationError error : validationErrors) { + LOGGER.error("Validation error, attribute: '" + error.printAttribute() + + "', message: '" + error.getMessage() + "'."); + error("Validation error, attribute: '" + error.printAttribute() + + "', message: '" + error.getMessage() + "'."); + } + + target.add(getFeedbackPanel()); + return true; + } + return false; + } + + @Override + public void startProcessing(AjaxRequestTarget target, OperationResult result) { + LOGGER.trace("startProcessing called, making main panel invisible"); + mainPanel.setVisible(false); + target.add(mainPanel); + } + + @NotNull + protected ModelExecuteOptions getOptions(boolean previewOnly) { + ModelExecuteOptions options = mainPanel.getExecuteChangeOptionsDto().createOptions(); + if (previewOnly) { + options.getOrCreatePartialProcessing().setApprovals(PartialProcessingTypeType.PROCESS); + } + return options; + } + + protected void prepareObjectForAdd(PrismObject object) throws SchemaException { + + } + + protected void prepareObjectDeltaForModify(ObjectDelta objectDelta) throws SchemaException { + + } + + protected List> getAdditionalModifyDeltas(OperationResult result) { + return null; + } + + protected boolean executeForceDelete(PrismObjectWrapper userWrapper, Task task, ModelExecuteOptions options, + OperationResult parentResult) { + return isForce(); + } + + protected boolean isForce() { + return getMainPanel().getExecuteChangeOptionsDto().isForce(); + } + + protected boolean isKeepDisplayingResults() { + return getMainPanel().getExecuteChangeOptionsDto().isKeepDisplayingResults(); + } + + protected boolean isSaveInBackground(){ + return getMainPanel().getExecuteChangeOptionsDto().isSaveInBackground(); + } + + protected Collection performCustomValidation(PrismObject object, + Collection> deltas) throws SchemaException { + Collection errors = null; + + if (object == null) { + if (getObjectWrapper() != null && getObjectWrapper().getObjectOld() != null) { + object = getObjectWrapper().getObjectOld().clone(); // otherwise original object could get corrupted e.g. by applying the delta below + + for (ObjectDelta delta : deltas) { + // because among deltas there can be also ShadowType deltas + if (UserType.class.isAssignableFrom(delta.getObjectTypeClass())) { + delta.applyTo(object); + } + } + } + } else { + object = object.clone(); + } + + performAdditionalValidation(object, deltas, errors); + + for (MidpointFormValidator validator : getFormValidatorRegistry().getValidators()) { + if (errors == null) { + errors = validator.validateObject(object, deltas); + } else { + errors.addAll(validator.validateObject(object, deltas)); + } + } + + return errors; + } + + protected void performAdditionalValidation(PrismObject object, + Collection> deltas, Collection errors) throws SchemaException { + + } + + public List getObjectFormTypes() { + Task task = createSimpleTask(OPERATION_LOAD_GUI_CONFIGURATION); + OperationResult result = task.getResult(); + CompiledGuiProfile adminGuiConfiguration; + try { + adminGuiConfiguration = getModelInteractionService().getCompiledGuiProfile(task, result); + } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { + throw new SystemException("Cannot load GUI configuration: "+e.getMessage(), e); + } + ObjectFormsType objectFormsType = adminGuiConfiguration.getObjectForms(); + if (objectFormsType == null) { + return null; + } + List objectForms = objectFormsType.getObjectForm(); + if (objectForms == null || objectForms.isEmpty()) { + return objectForms; + } + List validObjectForms = new ArrayList<>(); + for (ObjectFormType objectForm: objectForms) { + if (isSupportedObjectType(objectForm.getType())) { + validObjectForms.add(objectForm); + } + } + return validObjectForms; + } + + protected boolean isSupportedObjectType(QName type) { + ObjectTypes objectType = ObjectTypes.getObjectType(getCompileTimeClass()); + return QNameUtil.match(objectType.getTypeQName(),type); + } + + public void setSaveOnConfigure(boolean saveOnConfigure) { + this.saveOnConfigure = saveOnConfigure; + } + + public boolean isSaveOnConfigure() { + return saveOnConfigure; + } + + public boolean isForcedPreview() { + GuiObjectDetailsPageType objectDetails = getCompiledGuiProfile().findObjectDetailsConfiguration(getCompileTimeClass()); + return objectDetails != null && DetailsPageSaveMethodType.FORCED_PREVIEW.equals(objectDetails.getSaveMethod()); + } + + //TODO moved from PageAdminFocus.. maybe we need PageAssignmentHolderDetails? + @Override + public void finishProcessing(AjaxRequestTarget target, OperationResult result, boolean returningFromAsync) { + + if (previewRequested) { + finishPreviewProcessing(target, result); + return; + } + if (result.isSuccess() && getDelta() != null && SecurityUtils.getPrincipalUser().getOid().equals(getDelta().getOid())) { + Session.get().setLocale(WebModelServiceUtils.getLocale()); + LOGGER.debug("Using {} as locale", getLocale()); + WebSession.get().getClientInfo().getProperties(). + setTimeZone(WebModelServiceUtils.getTimezone()); + LOGGER.debug("Using {} as time zone", WebSession.get().getClientInfo().getProperties().getTimeZone()); + } + boolean focusAddAttempted = getDelta() != null && getDelta().isAdd(); + boolean focusAddSucceeded = focusAddAttempted && StringUtils.isNotEmpty(getDelta().getOid()); + + // we don't want to allow resuming editing if a new focal object was created (on second 'save' there would be a conflict with itself) + // and also in case of partial errors, like those related to projections (many deltas would be already executed, and this could cause problems on second 'save'). + boolean canContinueEditing = !focusAddSucceeded && result.isFatalError(); + + boolean canExitPage; + if (returningFromAsync) { + canExitPage = getProgressPanel().isAllSuccess() || result.isInProgress() || result.isHandledError(); // if there's at least a warning in the progress table, we would like to keep the table open + } else { + canExitPage = !canContinueEditing; // no point in staying on page if we cannot continue editing (in synchronous case i.e. no progress table present) + } + + if (!isKeepDisplayingResults() && canExitPage) { + showResult(result); + redirectBack(); + } else { + if (returningFromAsync) { + getProgressPanel().showBackButton(target); + getProgressPanel().hideAbortButton(target); + } + showResult(result); + target.add(getFeedbackPanel()); + + if (canContinueEditing) { + getProgressPanel().hideBackButton(target); + getProgressPanel().showContinueEditingButton(target); + } + } + } + + private void finishPreviewProcessing(AjaxRequestTarget target, OperationResult result) { + getMainPanel().setVisible(true); + getProgressPanel().hide(); + getProgressPanel().hideAbortButton(target); + getProgressPanel().hideBackButton(target); + getProgressPanel().hideContinueEditingButton(target); + + showResult(result); + target.add(getFeedbackPanel()); + + Map, ModelContext> modelContextMap = new LinkedHashMap<>(); + modelContextMap.put(getObjectWrapper().getObject(), getProgressPanel().getPreviewResult()); + + processAdditionalFocalObjectsForPreview(modelContextMap); + + navigateToNext(new PagePreviewChanges(modelContextMap, getModelInteractionService())); + } + + protected void processAdditionalFocalObjectsForPreview(Map, ModelContext> modelContextMap){ + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java index 3c4332850b8..67e6061a71b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java @@ -582,15 +582,7 @@ private TaskType getTask(){ protected Class getRestartResponsePage() { return PageTasks.class; } - - @Override - public void finishProcessing(AjaxRequestTarget target, OperationResult result, boolean returningFromAsync) { - if (!isKeepDisplayingResults()) { - showResult(result); - redirectBack(); - } - } - + @Override public void continueEditing(AjaxRequestTarget target) { From 65c8e24695633355f2b5466ea20160cd3442eefe Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Fri, 6 Mar 2020 16:58:33 +0100 Subject: [PATCH 16/55] removing other items (not relevant for archetyped task) --- .../000-system-configuration.xml | 85 +------------------ 1 file changed, 1 insertion(+), 84 deletions(-) diff --git a/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml b/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml index 16abb199a58..79b9339bf5e 100644 --- a/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml +++ b/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml @@ -488,90 +488,7 @@ stalledSince - - 990 - - - - - objectRef - - - extension/mext:objectType - - - extension/mext:diagnose - - - extension/mext:fix - - - extension/mext:duplicateShadowsResolver - - - extension/mext:checkDuplicatesOnPrimaryIdentifiersOnly - - - extension/mext:dryRun - - - extension/mext:retryLiveSyncErrors - - - extension/mext:freshnessInterval - - - extension/mext:finishOperationsOnly - - - extension/mext:lastScanTimestamp - - - extension/mext:searchOptions - - - extension/mext:useRepositoryDirectly - - - extension/mext:iterationMethod - - - extension/mext:objectDelta - - - extension/mext:objectDeltas - - - extension/mext:executeOptions - - - extension/mext:filename - - - extension/mext:endpoint - - - extension/mext:optionRaw - - - extension/mext:objectclass - - - extension/mext:kind - - - extension/mext:intent - - - extension/mext:objectQuery - - - extension/mext:updateLiveSyncTokenInDryRun - - - extension/mext:modelExecuteOptions - - + From a30ecaafa648564f619c3d7e3936a66300c3b61e Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 17:54:03 +0100 Subject: [PATCH 17/55] more test cleanup, TEST_NAME down under 2000 occurrences :-) --- model/model-intest/pom.xml | 5 + .../intest/TestUserTemplateWithRanges.java | 16 +- .../intest/archetypes/TestArchetypes.java | 57 ---- .../async/TestAsyncUpdateGrouperJson.java | 1 - .../intest/async/TestAsyncUpdateUcf.java | 34 +-- .../model/intest/async/TestNotifyChange.java | 21 +- .../intest/gensync/TestRoleEntitlement.java | 167 +++-------- .../intest/importer/AbstractImportTest.java | 15 +- .../AbstractDirectManualResourceTest.java | 36 --- .../manual/AbstractManualResourceTest.java | 7 +- .../model/intest/manual/TestSemiManual.java | 2 - .../intest/manual/TestSemiManualGrouping.java | 1 - .../mapping/TestMappingAutoInbound.java | 24 -- .../intest/mapping/TestMappingInbound.java | 208 ++++++-------- .../model/intest/misc/TestMigration.java | 8 - .../midpoint/model/intest/misc/TestMisc.java | 134 ++------- .../intest/misc/TestUuidNonUniqueName.java | 79 +++--- .../intest/negative/TestAssignmentErrors.java | 110 +++----- .../intest/negative/TestBrokenResources.java | 262 ++++++------------ .../negative/TestModelWebServiceNegative.java | 37 +-- .../model/intest/orgstruct/TestOrgStruct.java | 239 ++++------------ .../intest/orgstruct/TestOrgStructMeta.java | 25 +- .../test/AbstractModelIntegrationTest.java | 56 ++-- 23 files changed, 442 insertions(+), 1102 deletions(-) diff --git a/model/model-intest/pom.xml b/model/model-intest/pom.xml index 4aaba738eec..77520674d96 100644 --- a/model/model-intest/pom.xml +++ b/model/model-intest/pom.xml @@ -244,6 +244,11 @@ testng test + + org.assertj + assertj-core + test + com.evolveum.midpoint.tools test-ng diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java index 4a9da91f041..33e10fa5971 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplateWithRanges.java @@ -81,10 +81,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100RecomputeElaine() throws Exception { - final String TEST_NAME = "test100RecomputeElaine"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -106,10 +104,8 @@ public void test100RecomputeElaine() throws Exception { */ @Test public void test110ChangeManagerAndRecomputeElaine() throws Exception { - final String TEST_NAME = "test110ChangeManagerAndRecomputeElaine"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -133,10 +129,8 @@ public void test110ChangeManagerAndRecomputeElaine() throws Exception { */ @Test public void test120RestoreManagerAndRecomputeElaineAgain() throws Exception { - final String TEST_NAME = "test120RestoreManagerAndRecomputeElaineAgain"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assignOrg(USER_ELAINE_OID, ORG_GOVERNOR_OFFICE_OID, null); @@ -164,10 +158,8 @@ public void test120RestoreManagerAndRecomputeElaineAgain() throws Exception { */ @Test public void test140ChangeManagerAndRecomputeElaineAgain() throws Exception { - final String TEST_NAME = "test140ChangeManagerAndRecomputeElaineAgain"; - // GIVEN - Task task = taskManager.createTaskInstance(TestUserTemplateWithRanges.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java index 6d7b95dad37..0274be4004e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/archetypes/TestArchetypes.java @@ -35,10 +35,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * @author Radovan Semancik - * - */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestArchetypes extends AbstractArchetypesTest { @@ -125,11 +121,6 @@ protected File getSystemConfigurationFile() { */ @Test public void test020SanityJack() throws Exception { - final String TEST_NAME = "test020SanityJack"; - - Task task = getTestTask(); - OperationResult result = task.getResult(); - PrismObject user = assertUserBefore(USER_JACK_OID) .assertFullName(USER_JACK_FULL_NAME) .getObject(); @@ -139,8 +130,6 @@ public void test020SanityJack() throws Exception { @Test public void test050AddArchetypeTest() throws Exception { - final String TEST_NAME = "test050AddArchetypeTest"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -158,8 +147,6 @@ public void test050AddArchetypeTest() throws Exception { @Test public void test060AddArchetypesAndRoles() throws Exception { - final String TEST_NAME = "test060AddArchetypesAndRoles"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -197,8 +184,6 @@ public void test060AddArchetypesAndRoles() throws Exception { @Test public void test070AssignGuybrushUserAdministrator() throws Exception { - final String TEST_NAME = "test070AssignGuybrushUserAdministrator"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -216,8 +201,6 @@ public void test070AssignGuybrushUserAdministrator() throws Exception { @Test public void test100AssignJackArchetypeEmployee() throws Exception { - final String TEST_NAME = "test100AssignJackArchetypeEmployee"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -259,8 +242,6 @@ private String costCenterEmployee() { @Test public void test102SearchEmployeeArchetypeRef() throws Exception { - final String TEST_NAME = "test102SearchEmployeeArchetypeRef"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -296,8 +277,6 @@ public void test102SearchEmployeeArchetypeRef() throws Exception { @Test public void test104GetGuybryshCompiledGuiProfile() throws Exception { - final String TEST_NAME = "test104GetGuybryshCompiledGuiProfile"; - // GIVEN login(USER_GUYBRUSH_USERNAME); @@ -361,8 +340,6 @@ public void test104GetGuybryshCompiledGuiProfile() throws Exception { @Test public void test109UnassignJackArchetypeEmployee() throws Exception { - final String TEST_NAME = "test109UnassignJackArchetypeEmployee"; - loginAdministrator(); Task task = getTestTask(); @@ -395,8 +372,6 @@ public void test109UnassignJackArchetypeEmployee() throws Exception { @Test public void test110AssignJackRoleEmployeeBase() throws Exception { - final String TEST_NAME = "test110AssignJackRoleEmployeeBase"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -450,8 +425,6 @@ public void test110AssignJackRoleEmployeeBase() throws Exception { @Test public void test115UnassignJackRoleEmployeeBase() throws Exception { - final String TEST_NAME = "test115UnassignJackRoleEmployeeBase"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -493,8 +466,6 @@ public void test115UnassignJackRoleEmployeeBase() throws Exception { @Test public void test120AssignJackArchetypeTest() throws Exception { - final String TEST_NAME = "test120AssignJackArchetypeTest"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -528,8 +499,6 @@ public void test120AssignJackArchetypeTest() throws Exception { @Test public void test129UnassignJackArchetypeTest() throws Exception { - final String TEST_NAME = "test129UnassignJackArchetypeTest"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -559,8 +528,6 @@ public void test129UnassignJackArchetypeTest() throws Exception { */ @Test public void test130AssignJackArchetypeContractor() throws Exception { - final String TEST_NAME = "test130AssignJackArchetypeContractor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -591,8 +558,6 @@ public void test130AssignJackArchetypeContractor() throws Exception { */ @Test public void test132JackContractorRecompute() throws Exception { - final String TEST_NAME = "test132JackContractorRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -624,8 +589,6 @@ public void test132JackContractorRecompute() throws Exception { */ @Test public void test135UnassignJackArchetypeContractor() throws Exception { - final String TEST_NAME = "test135UnassignJackArchetypeContractor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -658,8 +621,6 @@ public void test135UnassignJackArchetypeContractor() throws Exception { */ @Test public void test137JackEmpnoAndRecompute() throws Exception { - final String TEST_NAME = "test137JackEmpnoAndRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -694,8 +655,6 @@ public void test137JackEmpnoAndRecompute() throws Exception { */ @Test public void test140AddMeathookContractor() throws Exception { - final String TEST_NAME = "test140AddMeathookContractor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -728,8 +687,6 @@ public void test140AddMeathookContractor() throws Exception { */ @Test public void test150AddWannabe() throws Exception { - final String TEST_NAME = "test150AddWannabe"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -763,8 +720,6 @@ public void test150AddWannabe() throws Exception { */ @Test public void test160AddSelfMadeMan() throws Exception { - final String TEST_NAME = "test160AddSelfMadeMan"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -796,8 +751,6 @@ public void test160AddSelfMadeMan() throws Exception { */ @Test public void test162AddFraudster() throws Exception { - final String TEST_NAME = "test162AddFraudster"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -825,8 +778,6 @@ public void test162AddFraudster() throws Exception { @Test public void test200AssignJackBarbossaArchetypeEmployee() throws Exception { - final String TEST_NAME = "test200AssignJackBarbossaArchetypeEmployee"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -850,8 +801,6 @@ public void test200AssignJackBarbossaArchetypeEmployee() throws Exception { @Test public void test202GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exception { - final String TEST_NAME = "test202GetGuybryshCompiledGuiProfileActiveEmployeesView"; - // GIVEN login(USER_GUYBRUSH_USERNAME); @@ -886,8 +835,6 @@ public void test202GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exc @Test public void test203DisableBarbossa() throws Exception { - final String TEST_NAME = "test203DisableBarbossa"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -910,8 +857,6 @@ public void test203DisableBarbossa() throws Exception { @Test public void test205GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exception { - final String TEST_NAME = "test205GetGuybryshCompiledGuiProfileActiveEmployeesView"; - // GIVEN login(USER_GUYBRUSH_USERNAME); @@ -946,8 +891,6 @@ public void test205GetGuybryshCompiledGuiProfileActiveEmployeesView() throws Exc @Test public void test300jackAssignArchetypeRaw() throws Exception { - final String TEST_NAME = "test300jackAssignArchetypeRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java index 3c87a3e8a2f..efb8a608309 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateGrouperJson.java @@ -75,7 +75,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; Task task = getTestTask(); OperationResult testResultGrouper = modelService.testResource(RESOURCE_GROUPER_OID, task); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java index 9f3e449ff30..a57f3468828 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestAsyncUpdateUcf.java @@ -72,24 +72,18 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult testResultGrouper = modelService.testResource(RESOURCE_GROUPER_OID, task); TestUtil.assertSuccess(testResultGrouper); } - private Task createTestTask(String TEST_NAME) { - return taskManager.createTaskInstance(TestAsyncUpdateUcf.class.getName() + "." + TEST_NAME); - } - /** * Shadow ADD delta for banderson. */ @Test public void test100AddAnderson() throws Exception { - final String TEST_NAME = "test100AddAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -127,8 +121,7 @@ public void test100AddAnderson() throws Exception { */ @Test public void test110AddAlumniAndStaff() throws Exception { - final String TEST_NAME = "test110AddAlumni"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -173,8 +166,7 @@ public void test110AddAlumniAndStaff() throws Exception { */ @Test public void test120AddWhite() throws Exception { - final String TEST_NAME = "test120AddWhite"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -212,8 +204,7 @@ public void test120AddWhite() throws Exception { */ @Test public void test200AddAlumniForAnderson() throws Exception { - final String TEST_NAME = "test200AddAlumniForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -251,8 +242,7 @@ public void test200AddAlumniForAnderson() throws Exception { */ @Test public void test210AddStaffForAnderson() throws Exception { - final String TEST_NAME = "test210AddStaffForAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -290,8 +280,7 @@ public void test210AddStaffForAnderson() throws Exception { */ @Test public void test220AddAlumniForLewis() throws Exception { - final String TEST_NAME = "test220AddAlumniForLewis"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -329,8 +318,7 @@ public void test220AddAlumniForLewis() throws Exception { */ @Test public void test230MentionLewis() throws Exception { - final String TEST_NAME = "test230MentionLewis"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -368,8 +356,7 @@ public void test230MentionLewis() throws Exception { */ @Test public void test300DeleteAnderson() throws Exception { - final String TEST_NAME = "test300DeleteAnderson"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -399,8 +386,7 @@ public void test300DeleteAnderson() throws Exception { */ @Test public void test310DeleteStaff() throws Exception { - final String TEST_NAME = "test310DeleteStaff"; - Task task = createTestTask(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java index 48d0fd78edf..f3bea3ea64c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/async/TestNotifyChange.java @@ -86,8 +86,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultGrouper = modelService.testResource(RESOURCE_GROUPER_OID, task); TestUtil.assertSuccess(testResultGrouper); @@ -98,8 +97,7 @@ public void test000Sanity() throws Exception { */ @Test public void test100AddAnderson() throws Exception { - final String TEST_NAME = "test100AddAnderson"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -135,8 +133,7 @@ public void test100AddAnderson() throws Exception { */ @Test public void test105AddLewis() throws Exception { - final String TEST_NAME = "test105AddLewis"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -175,8 +172,7 @@ public void test105AddLewis() throws Exception { */ @Test public void test110AddAlumni() throws Exception { - final String TEST_NAME = "test110AddAlumni"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -212,8 +208,7 @@ public void test110AddAlumni() throws Exception { */ @Test public void test120AddStaff() throws Exception { - final String TEST_NAME = "test120AddStaff"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -249,8 +244,7 @@ public void test120AddStaff() throws Exception { */ @Test public void test200AddGroupsForAnderson() throws Exception { - final String TEST_NAME = "test200AddGroupsForAnderson"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN @@ -286,8 +280,7 @@ public void test200AddGroupsForAnderson() throws Exception { */ @Test public void test210AddGroupsForLewis() throws Exception { - final String TEST_NAME = "test210AddGroupsForLewis"; - Task task = taskManager.createTaskInstance(TestNotifyChange.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // GIVEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java index a168e1316c3..7a98c07e36c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/gensync/TestRoleEntitlement.java @@ -6,53 +6,53 @@ */ package com.evolveum.midpoint.model.intest.gensync; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.util.Collection; -import javax.xml.datatype.XMLGregorianCalendar; +import org.apache.commons.lang.StringUtils; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.AssertJUnit; +import org.testng.annotations.Test; import com.evolveum.icf.dummy.resource.DummyGroup; import com.evolveum.midpoint.audit.api.AuditEventStage; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.*; +import com.evolveum.midpoint.prism.Containerable; +import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.util.PrismAsserts; +import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.ObjectDeltaOperation; import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.StringUtils; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.AssertJUnit; -import org.testng.annotations.Test; - -import com.evolveum.midpoint.prism.util.PrismAsserts; -import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.MiscUtil; - /** * Generic synchronization test. We create role and assign a resource to it. * Entitlement (group) should be created. * * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRoleEntitlement extends AbstractGenericSyncTest { @@ -60,8 +60,6 @@ public class TestRoleEntitlement extends AbstractGenericSyncTest { @Test public void test050GetRolePirate() throws Exception { - final String TEST_NAME = "test050GetRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -78,16 +76,14 @@ public void test050GetRolePirate() throws Exception { protected void assertRolePirate(PrismObject role) { assertObjectSanity(role); - assertEquals("Wrong "+role+" OID (prism)", ROLE_PIRATE_OID, role.getOid()); + assertEquals("Wrong " + role + " OID (prism)", ROLE_PIRATE_OID, role.getOid()); RoleType roleType = role.asObjectable(); - assertEquals("Wrong "+role+" OID (jaxb)", ROLE_PIRATE_OID, roleType.getOid()); - PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", "Pirate", roleType.getName()); + assertEquals("Wrong " + role + " OID (jaxb)", ROLE_PIRATE_OID, roleType.getOid()); + PrismAsserts.assertEqualsPolyString("Wrong " + role + " name", "Pirate", roleType.getName()); } @Test public void test100ModifyRoleAddEntitlement() throws Exception { - final String TEST_NAME = "test100ModifyRoleAddEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -107,14 +103,12 @@ public void test100ModifyRoleAddEntitlement() throws Exception { prepareNotifications(); dummyTransport.clearMessages(); notificationManager.setDisabled(false); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); // WHEN modelService.executeChanges(deltas, null, task, result); // THEN assertSuccess(result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); // Check accountRef PrismObject rolePirate = modelService.getObject(RoleType.class, ROLE_PIRATE_OID, null, task, result); @@ -152,8 +146,6 @@ public void test100ModifyRoleAddEntitlement() throws Exception { @Test public void test101GetGroup() throws Exception { - final String TEST_NAME = "test101GetGroup"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -165,7 +157,7 @@ public void test101GetGroup() throws Exception { dummyGroup.replaceAttributeValue(DummyResourceContoller.DUMMY_GROUP_ATTRIBUTE_DESCRIPTION, "Bloodthirsty Pirates"); // WHEN - PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, null , task, result); + PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, null, task, result); // THEN display("Group shadow (model)", shadow); @@ -181,8 +173,6 @@ public void test101GetGroup() throws Exception { @Test public void test102GetGroupNoFetch() throws Exception { - final String TEST_NAME = "test102GetGroupNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -191,7 +181,7 @@ public void test102GetGroupNoFetch() throws Exception { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createNoFetch()); // WHEN - PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options , task, result); + PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options, task, result); display("Account", shadow); display("Account def", shadow.getDefinition()); @@ -206,8 +196,6 @@ public void test102GetGroupNoFetch() throws Exception { @Test public void test103GetGroupRaw() throws Exception { - final String TEST_NAME = "test103GetGroupRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -215,7 +203,7 @@ public void test103GetGroupRaw() throws Exception { Collection> options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); // WHEN - PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options , task, result); + PrismObject shadow = modelService.getObject(ShadowType.class, groupOid, options, task, result); display("Account", shadow); display("Account def", shadow.getDefinition()); @@ -230,8 +218,6 @@ public void test103GetGroupRaw() throws Exception { @Test public void test108ModifyRoleAddEntitlementAgain() throws Exception { - final String TEST_NAME = "test108ModifyRoleAddEntitlementAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -245,7 +231,7 @@ public void test108ModifyRoleAddEntitlementAgain() throws Exception { linkRefVal.setObject(group); ReferenceDelta groupDelta = prismContext.deltaFactory().reference().createModificationAdd(RoleType.F_LINK_REF, getRoleDefinition(), linkRefVal); roleDelta.addModification(groupDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(roleDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(roleDelta); dummyAuditService.clear(); @@ -276,8 +262,6 @@ public void test108ModifyRoleAddEntitlementAgain() throws Exception { @Test public void test110GetRoleResolveEntitlement() throws Exception { - final String TEST_NAME = "test110GetRoleResolveEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -304,8 +288,6 @@ public void test110GetRoleResolveEntitlement() throws Exception { @Test public void test111GetRoleResolveEntitlement() throws Exception { - final String TEST_NAME = "test111GetRoleResolveEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -336,8 +318,6 @@ public void test111GetRoleResolveEntitlement() throws Exception { @Test public void test112GetRoleResolveEntitlementNoFetch() throws Exception { - final String TEST_NAME = "test112GetRoleResolveEntitlementNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -345,8 +325,8 @@ public void test112GetRoleResolveEntitlementNoFetch() throws Exception { Collection> options = schemaHelper.getOperationOptionsBuilder() .item(UserType.F_LINK_REF) - .resolve() - .noFetch() + .resolve() + .noFetch() .build(); // WHEN @@ -364,11 +344,8 @@ public void test112GetRoleResolveEntitlementNoFetch() throws Exception { TestUtil.assertSuccess("getObject result", result); } - @Test public void test119ModifyRoleDeleteEntitlement() throws Exception { - final String TEST_NAME = "test119ModifyRoleDeleteEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -381,7 +358,7 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { .createEmptyModifyDelta(RoleType.class, ROLE_PIRATE_OID); ReferenceDelta linkDelta = prismContext.deltaFactory().reference().createModificationDelete(RoleType.F_LINK_REF, getUserDefinition(), group); roleDelta.addModification(linkDelta); - Collection> deltas = (Collection)MiscUtil.createCollection(roleDelta); + Collection> deltas = (Collection) MiscUtil.createCollection(roleDelta); prepareNotifications(); @@ -400,7 +377,7 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { // Check is shadow is gone try { - PrismObject shadow = repositoryService.getObject(ShadowType.class, groupOid, null, result); + repositoryService.getObject(ShadowType.class, groupOid, null, result); AssertJUnit.fail("Shadow " + groupOid + " still exists"); } catch (ObjectNotFoundException e) { // This is OK @@ -409,7 +386,7 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { // Check if dummy resource account is gone assertNoDummyGroup(GROUP_PIRATE_DUMMY_NAME); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -424,8 +401,6 @@ public void test119ModifyRoleDeleteEntitlement() throws Exception { @Test public void test120AddEntitlement() throws Exception { - final String TEST_NAME = "test120AddEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -434,8 +409,6 @@ public void test120AddEntitlement() throws Exception { PrismObject group = PrismTestUtil.parseObject(GROUP_PIRATE_DUMMY_FILE); ObjectDelta groupDelta = DeltaFactory.Object.createAddDelta(group); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); Collection> executedChanges = executeChanges(groupDelta, null, task, result); @@ -443,7 +416,6 @@ public void test120AddEntitlement() throws Exception { // THEN then(); assertSuccess(result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); groupOid = ObjectDeltaOperation.findAddDeltaOid(executedChanges, group); assertNotNull("No account OID in resulting delta", groupOid); @@ -478,8 +450,6 @@ public void test120AddEntitlement() throws Exception { @Test public void test121ModifyRoleLinkEntitlement() throws Exception { - final String TEST_NAME = "test121ModifyRoleLinkEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -527,11 +497,8 @@ public void test121ModifyRoleLinkEntitlement() throws Exception { dummyAuditService.assertExecutionSuccess(); } - @Test public void test128ModifyRoleUnlinkEntitlement() throws Exception { - final String TEST_NAME = "test128ModifyRoleUnlinkEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -582,8 +549,6 @@ public void test128ModifyRoleUnlinkEntitlement() throws Exception { @Test public void test129DeleteEntitlement() throws Exception { - final String TEST_NAME = "test129DeleteEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -623,8 +588,6 @@ public void test129DeleteEntitlement() throws Exception { @Test public void test131ModifyRoleAssignEntitlement() throws Exception { - final String TEST_NAME = "test131ModifyRoleAssignEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -684,8 +647,6 @@ public void test131ModifyRoleAssignEntitlement() throws Exception { */ @Test public void test132ModifyEntitlement() throws Exception { - final String TEST_NAME = "test132ModifyEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -710,7 +671,7 @@ public void test132ModifyEntitlement() throws Exception { display("Role after change execution", role); assertEquals("Wrong role description", ROLE_PIRATE_DESCRIPTION, role.asObjectable().getDescription()); // reflected by inbound - PrismAsserts.assertPropertyValue(role,ROLE_EXTENSION_COST_CENTER_PATH, "MELEE123"); + PrismAsserts.assertPropertyValue(role, ROLE_EXTENSION_COST_CENTER_PATH, "MELEE123"); assertLinks(role, 1); groupOid = getSingleLinkOid(role); @@ -748,8 +709,6 @@ public void test132ModifyEntitlement() throws Exception { @Test public void test139ModifyRoleUnassignEntitlement() throws Exception { - final String TEST_NAME = "test139ModifyRoleUnassignEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -797,8 +756,6 @@ public void test139ModifyRoleUnassignEntitlement() throws Exception { */ @Test public void test151ModifyRoleAssignEntitlementRelativeEnforcement() throws Exception { - final String TEST_NAME = "test151ModifyRoleAssignEntitlementRelativeEnforcement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -808,15 +765,12 @@ public void test151ModifyRoleAssignEntitlementRelativeEnforcement() throws Excep ShadowKindType.ENTITLEMENT, "group", true); Collection> deltas = MiscSchemaUtil.createCollection(assignmentDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -857,11 +811,8 @@ public void test151ModifyRoleAssignEntitlementRelativeEnforcement() throws Excep */ @Test public void test158ModifyRoleUnassignEntitlementRelativeEnforcement() throws Exception { - final String TEST_NAME = "test158ModifyRoleUnassignEntitlementRelativeEnforcement"; - // GIVEN - Task task = taskManager.createTaskInstance(TestRoleEntitlement.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); prepareTest(AssignmentPolicyEnforcementType.RELATIVE); @@ -907,8 +858,6 @@ public void test158ModifyRoleUnassignEntitlementRelativeEnforcement() throws Exc */ @Test public void test160ModifyRolePropertyAndAssignEntitlement() throws Exception { - final String TEST_NAME = "test160ModifyRolePropertyAndAssignEntitlement"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -919,15 +868,12 @@ public void test160ModifyRolePropertyAndAssignEntitlement() throws Exception { roleDelta.addModificationReplaceProperty(RoleType.F_DESCRIPTION, "Band of Bloodthirsty Bashers"); Collection> deltas = MiscSchemaUtil.createCollection(roleDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -968,8 +914,6 @@ public void test160ModifyRolePropertyAndAssignEntitlement() throws Exception { */ @Test public void test161ModifyRole() throws Exception { - final String TEST_NAME = "test161ModifyRole"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -979,15 +923,12 @@ public void test161ModifyRole() throws Exception { ROLE_PIRATE_OID, RoleType.F_DESCRIPTION, ROLE_PIRATE_DESCRIPTION); Collection> deltas = MiscSchemaUtil.createCollection(roleDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -997,13 +938,11 @@ public void test161ModifyRole() throws Exception { // Check shadow PrismObject shadow = repositoryService.getObject(ShadowType.class, groupOid, null, result); assertDummyGroupShadowRepo(shadow, groupOid, GROUP_PIRATE_DUMMY_NAME); -// assertEnableTimestampShadow(shadow, startTime, endTime); // Check group PrismObject shadowModel = modelService.getObject(ShadowType.class, groupOid, null, task, result); display("Entitlement shadow after", shadowModel); assertDummyGroupShadowModel(shadowModel, groupOid, GROUP_PIRATE_DUMMY_NAME); -// assertEnableTimestampShadow(shadowModel, startTime, endTime); // Check group in dummy resource assertDummyGroup(GROUP_PIRATE_DUMMY_NAME, ROLE_PIRATE_DESCRIPTION); @@ -1024,8 +963,6 @@ public void test161ModifyRole() throws Exception { @Test public void test180RenameRole() throws Exception { - final String TEST_NAME = "test180RenameRole"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1035,15 +972,12 @@ public void test180RenameRole() throws Exception { ROLE_PIRATE_OID, RoleType.F_NAME, PrismTestUtil.createPolyString("Privateers")); Collection> deltas = MiscSchemaUtil.createCollection(roleDelta); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN modelService.executeChanges(deltas, null, task, result); // THEN result.computeStatus(); TestUtil.assertSuccess("executeChanges result", result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); PrismObject role = getRole(ROLE_PIRATE_OID); display("Role after change execution", role); @@ -1069,7 +1003,7 @@ public void test180RenameRole() throws Exception { // Just to be on a safe side, this is uppercase assertNoDummyGroup(ROLE_PIRATE_NAME); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -1086,8 +1020,6 @@ public void test180RenameRole() throws Exception { */ @Test public void test199DeleteRole() throws Exception { - final String TEST_NAME = "test199DeleteRole"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1105,7 +1037,7 @@ public void test199DeleteRole() throws Exception { TestUtil.assertSuccess("executeChanges result", result); try { - PrismObject role = getRole(ROLE_PIRATE_OID); + getRole(ROLE_PIRATE_OID); AssertJUnit.fail("Privateers are still alive!"); } catch (ObjectNotFoundException ex) { // This is OK @@ -1121,7 +1053,7 @@ public void test199DeleteRole() throws Exception { assertNoDummyGroup(GROUP_PIRATE_DUMMY_NAME); assertNoDummyGroup(ROLE_PIRATE_NAME); - // Check audit + // Check audit display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); dummyAuditService.assertSimpleRecordSanity(); @@ -1140,8 +1072,6 @@ public void test199DeleteRole() throws Exception { */ @Test public void test200AddRoleSwashbuckler() throws Exception { - final String TEST_NAME = "test200AddRoleSwashbuckler"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1150,8 +1080,6 @@ public void test200AddRoleSwashbuckler() throws Exception { PrismObject role = parseObject(ROLE_SWASHBUCKLER_FILE); ObjectDelta roleDelta = DeltaFactory.Object.createAddDelta(role); - XMLGregorianCalendar startTime = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); executeChanges(roleDelta, null, task, result); @@ -1159,7 +1087,6 @@ public void test200AddRoleSwashbuckler() throws Exception { // THEN then(); assertSuccess(result); - XMLGregorianCalendar endTime = clock.currentTimeXMLGregorianCalendar(); assertNotNull("No account OID in resulting delta", groupOid); // Check linkRef (should be none) @@ -1190,11 +1117,11 @@ public void test200AddRoleSwashbuckler() throws Exception { dummyAuditService.assertRecords(3); dummyAuditService.assertSimpleRecordSanity(); dummyAuditService.assertAnyRequestDeltas(); - dummyAuditService.assertExecutionDeltas(0,3); + dummyAuditService.assertExecutionDeltas(0, 3); dummyAuditService.assertHasDelta(0, ChangeType.ADD, RoleType.class); dummyAuditService.assertHasDelta(0, ChangeType.ADD, ShadowType.class); dummyAuditService.assertHasDelta(0, ChangeType.MODIFY, RoleType.class); // link - dummyAuditService.assertExecutionDeltas(1,1); + dummyAuditService.assertExecutionDeltas(1, 1); dummyAuditService.assertHasDelta(1, ChangeType.MODIFY, RoleType.class); // inbound dummyAuditService.assertTarget(ROLE_SWASHBUCKLER_OID); dummyAuditService.assertExecutionSuccess(); @@ -1205,15 +1132,13 @@ public void test200AddRoleSwashbuckler() throws Exception { */ @Test public void test210ModifyRoleSwashbucklerRiskLevel() throws Exception { - final String TEST_NAME = "test210ModifyRoleSwashbucklerRiskLevel"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); prepareTest(AssignmentPolicyEnforcementType.RELATIVE); assertRoleBefore(ROLE_SWASHBUCKLER_OID) - .extension() + .extension() .assertItems(PIRACY_COST_CENTER); // WHEN @@ -1225,12 +1150,12 @@ public void test210ModifyRoleSwashbucklerRiskLevel() throws Exception { assertSuccess(result); assertRoleAfter(ROLE_SWASHBUCKLER_OID) - .assertRiskLevel("99") - .extension() + .assertRiskLevel("99") + .extension() .assertItems(PIRACY_COST_CENTER, PIRACY_RISK_VECTOR) .containerSingle(PIRACY_RISK_VECTOR) - .assertPropertyEquals(PIRACY_RISK_VECTOR_RISK, "X") - .assertPropertyEquals(PIRACY_RISK_VECTOR_VALUE, 99); + .assertPropertyEquals(PIRACY_RISK_VECTOR_RISK, "X") + .assertPropertyEquals(PIRACY_RISK_VECTOR_VALUE, 99); } private void prepareTest(AssignmentPolicyEnforcementType enforcement) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java index ea2b2e2a02c..d399fee1965 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/importer/AbstractImportTest.java @@ -402,9 +402,8 @@ public void test006ImportUsersWithOverwriteKeepOid() throws Exception { @Test public void test020ImportTask() throws Exception { - final String TEST_NAME = "test020ImportTask"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(IMPORT_TASK_FILE_NAME, false)); @@ -446,9 +445,8 @@ public void test020ImportTask() throws Exception { @Test public void test030ImportResource() throws Exception { - final String TEST_NAME = "test030ImportResource"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_FILE_NAME, true)); @@ -496,9 +494,8 @@ public void test030ImportResource() throws Exception { @Test public void test031ReimportResource() throws Exception { - final String TEST_NAME = "test031ReimportResource"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_CHANGED_FILE_NAME, false)); @@ -550,9 +547,8 @@ public void test031ReimportResource() throws Exception { @Test public void test032ImportResourceOidAndFilter() throws Exception { - final String TEST_NAME = "test032ImportResourceOidAndFilter"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DERBY_FILE_NAME, false)); @@ -603,9 +599,8 @@ public void test032ImportResourceOidAndFilter() throws Exception { */ @Test public void test033ImportResourceDummyRuntime() throws Exception { - final String TEST_NAME = "test033ImportResourceDummyRuntime"; // GIVEN - Task task = taskManager.createTaskInstance(AbstractImportTest.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); FileInputStream stream = new FileInputStream(getFile(RESOURCE_DUMMY_RUNTIME_FILE_NAME, false)); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java index ceceffed8b4..f14763ad47f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractDirectManualResourceTest.java @@ -118,7 +118,6 @@ protected boolean isDirect() { */ @Test public void test220ModifyUserWillDisable() throws Exception { - final String TEST_NAME = "test220ModifyUserWillDisable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -195,7 +194,6 @@ public void test220ModifyUserWillDisable() throws Exception { */ @Test public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { - final String TEST_NAME = "test230ModifyAccountWillChangePasswordAndEnable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -283,7 +281,6 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { */ @Test public void test240CloseDisableCaseAndReadAccountWill() throws Exception { - final String TEST_NAME = "test240CloseDisableCaseAndReadAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -373,7 +370,6 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { */ @Test public void test250RecomputeWillAfter5min() throws Exception { - final String TEST_NAME = "test250RecomputeWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -460,7 +456,6 @@ public void test250RecomputeWillAfter5min() throws Exception { @Test public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test252UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -518,7 +513,6 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { - final String TEST_NAME = "test260ClosePasswordChangeCaseAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -622,7 +616,6 @@ public void test260ClosePasswordChangeCaseAndRecomputeWill() throws Exception { */ @Test public void test270RecomputeWillAfter7min() throws Exception { - final String TEST_NAME = "test130RefreshAccountWillAfter7min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -720,7 +713,6 @@ public void test270RecomputeWillAfter7min() throws Exception { @Test public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test272UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -778,7 +770,6 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test274RecomputeWillAfter22min() throws Exception { - final String TEST_NAME = "test292RecomputeWillAfter22min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -863,7 +854,6 @@ public void test274RecomputeWillAfter22min() throws Exception { */ @Test public void test280RecomputeWillAfter27min() throws Exception { - final String TEST_NAME = "test280RecomputeWillAfter27min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -936,7 +926,6 @@ public void test280RecomputeWillAfter27min() throws Exception { */ @Test public void test290RecomputeWillAfter32min() throws Exception { - final String TEST_NAME = "test290RecomputeWillAfter32min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -998,7 +987,6 @@ public void test290RecomputeWillAfter32min() throws Exception { @Test public void test300UnassignAccountWill() throws Exception { - final String TEST_NAME = "test300UnassignAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1074,7 +1062,6 @@ public void test300UnassignAccountWill() throws Exception { */ @Test public void test302RecomputeWill() throws Exception { - final String TEST_NAME = "test302RecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1144,7 +1131,6 @@ public void test302RecomputeWill() throws Exception { */ @Test public void test310CloseCaseAndReconcileWill() throws Exception { - final String TEST_NAME = "test310CloseCaseAndReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1209,7 +1195,6 @@ protected void assertUnassignedShadow(ShadowAsserter shadowModelAsserter, boo */ @Test public void test320RecomputeWillAfter5min() throws Exception { - final String TEST_NAME = "test320RecomputeWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1262,7 +1247,6 @@ public void test320RecomputeWillAfter5min() throws Exception { */ @Test public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { - final String TEST_NAME = "test330UpdateBackingStoreAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1325,7 +1309,6 @@ public void test330UpdateBackingStoreAndRecomputeWill() throws Exception { */ @Test public void test340RecomputeWillAfter25min() throws Exception { - final String TEST_NAME = "test340RecomputeWillAfter25min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1366,7 +1349,6 @@ public void test340RecomputeWillAfter25min() throws Exception { */ @Test public void test342RecomputeWillAfter35min() throws Exception { - final String TEST_NAME = "test342RecomputeWillAfter35min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1404,7 +1386,6 @@ public void test342RecomputeWillAfter35min() throws Exception { */ @Test public void test344RecomputeWillAfter165min() throws Exception { - final String TEST_NAME = "test344RecomputeWillAfter165min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1467,7 +1448,6 @@ public void test500AssignWillRoleOne() throws Exception { */ @Test public void test510UnassignWillRoleOne() throws Exception { - final String TEST_NAME = "test510UnassignWillRoleOne"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1537,7 +1517,6 @@ public void test510UnassignWillRoleOne() throws Exception { */ @Test public void test512ReconcileWill() throws Exception { - final String TEST_NAME = "test512ReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1607,7 +1586,6 @@ public void test512ReconcileWill() throws Exception { */ @Test public void test515CloseCasesAndReconcileWill() throws Exception { - final String TEST_NAME = "test515CloseCasesAndReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1707,7 +1685,6 @@ protected void assertWillUnassignPendingOperationCompleted(ShadowAsserter */ @Test public void test516RecomputeWillAfter20min() throws Exception { - final String TEST_NAME = "test516RecomputeWillAfter20min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1741,7 +1718,6 @@ public void test516RecomputeWillAfter20min() throws Exception { */ @Test public void test517RecomputeWillAfter50min() throws Exception { - final String TEST_NAME = "test517RecomputeWillAfter50min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1777,7 +1753,6 @@ public void test517RecomputeWillAfter50min() throws Exception { */ @Test public void test518RecomputeWillAfter180min() throws Exception { - final String TEST_NAME = "test518RecomputeWillAfter180min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1837,7 +1812,6 @@ public void test520AssignWillRoleOne() throws Exception { */ @Test public void test522AssignWillRoleTwoValidFrom() throws Exception { - final String TEST_NAME = "test522AssignWillRoleTwoValidFrom"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1870,7 +1844,6 @@ public void test522AssignWillRoleTwoValidFrom() throws Exception { */ @Test public void test524TwoHoursForRoleTwo() throws Exception { - final String TEST_NAME = "test524TwoHoursForRoleTwo"; // GIVEN clockForward("PT2H5M"); @@ -1938,7 +1911,6 @@ public void test524TwoHoursForRoleTwo() throws Exception { */ @Test public void test525CloseCasesAndReconcileWill() throws Exception { - final String TEST_NAME = "test525CloseCasesAndReconcileWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1975,7 +1947,6 @@ public void test525CloseCasesAndReconcileWill() throws Exception { */ @Test public void test526UnassignWillBothRoles() throws Exception { - final String TEST_NAME = "test526UnassignWillBothRoles"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2034,7 +2005,6 @@ protected void assertTest526Deltas(PrismObject shadowRepo, Operation @Test public void test528CloseCaseAndRecomputeWill() throws Exception { - final String TEST_NAME = "test528CloseCaseAndRecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2114,7 +2084,6 @@ public void test529CleanUp() throws Exception { */ @Test public void test800ImportShadowRefreshTask() throws Exception { - final String TEST_NAME = "test800ImportShadowRefreshTask"; // GIVEN // WHEN @@ -2129,8 +2098,6 @@ public void test800ImportShadowRefreshTask() throws Exception { @Test public void test810AssignAccountWill() throws Exception { - final String TEST_NAME = "test810AssignAccountWill"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2152,7 +2119,6 @@ public void test810AssignAccountWill() throws Exception { @Test public void test820AssignAccountJack() throws Exception { - final String TEST_NAME = "test820AssignAccountJack"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2189,7 +2155,6 @@ public void test820AssignAccountJack() throws Exception { @Test public void test830CloseCaseWillAndWaitForRefresh() throws Exception { - final String TEST_NAME = "test830CloseCaseWillAndWaitForRefresh"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2216,7 +2181,6 @@ public void test830CloseCaseWillAndWaitForRefresh() throws Exception { @Test public void test840AddToBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test840AddToBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java index e84c5cf1ecd..e7e000251e5 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java @@ -360,7 +360,7 @@ public void test016ParsedSchema() throws Exception { // THEN // The returned type should have the schema pre-parsed - assertNotNull(RefinedResourceSchemaImpl.hasParsedSchema(resourceType)); + assertTrue(RefinedResourceSchemaImpl.hasParsedSchema(resourceType)); // Also test if the utility method returns the same thing ResourceSchema resourceSchema = RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext); @@ -370,7 +370,7 @@ public void test016ParsedSchema() throws Exception { // Check whether it is reusing the existing schema and not parsing it all over again // Not equals() but == ... we want to really know if exactly the same // object instance is returned - assertTrue("Broken caching", resourceSchema == RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext)); + assertSame("Broken caching", resourceSchema, RefinedResourceSchemaImpl.getResourceSchema(resourceType, prismContext)); ObjectClassComplexTypeDefinition accountDef = resourceSchema.findObjectClassDefinition(RESOURCE_ACCOUNT_OBJECTCLASS); assertNotNull("Account definition is missing", accountDef); @@ -703,7 +703,6 @@ public void test103RunPropagation() throws Exception { @Test public void test104RecomputeWill() throws Exception { - final String TEST_NAME = "test104RecomputeWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2168,7 +2167,7 @@ protected void assertAttribute( assertAttribute(shadow.asObjectable(), attrName, expectedValues); } - protected void assertNoAttribute(PrismObject shadow, QName attrName) { + protected void assertNoAttribute(PrismObject shadow, QName attrName) { assertNoAttribute(shadow.asObjectable(), attrName); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java index 0565135974f..d1c9ef044f2 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManual.java @@ -36,8 +36,6 @@ @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestSemiManual extends AbstractDirectManualResourceTest { - protected static final String ATTR_DISABLED = "disabled"; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java index e18c11ba6af..b4e4921a978 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/TestSemiManualGrouping.java @@ -122,7 +122,6 @@ protected void assertShadowPassword(PrismObject shadow) { @Test @Override public void test400PhantomAccount() throws Exception { - final String TEST_NAME = "test400PhantomAccount"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java index 9dded5516b8..1aa62c982cf 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingAutoInbound.java @@ -63,8 +63,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100ImportFromResource() throws Exception { - final String TEST_NAME = "test100ImportFromResource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -111,8 +109,6 @@ public void test100ImportFromResource() throws Exception { */ @Test public void test110ModifyAccountTitleCraticAndReconcile() throws Exception { - final String TEST_NAME = "test110ModifyAccountTitleCraticAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -139,8 +135,6 @@ public void test110ModifyAccountTitleCraticAndReconcile() throws Exception { */ @Test public void test112ModifyAccountTitleDidacticGraphicAndReconcile() throws Exception { - final String TEST_NAME = "test112ModifyAccountTitleDidacticGraphicAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -169,8 +163,6 @@ public void test112ModifyAccountTitleDidacticGraphicAndReconcile() throws Except @Test public void test200ImportFromResourceAssociations() throws Exception { - final String TEST_NAME = "test200ImportFromResourceAssociations"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.RELATIVE, false); // GIVEN @@ -219,8 +211,6 @@ public void test200ImportFromResourceAssociations() throws Exception { @Test public void test300ModifyAccountDirectAssign() throws Exception { - final String TEST_NAME = "test300ModifyAccountDirectAssign"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -246,8 +236,6 @@ public void test300ModifyAccountDirectAssign() throws Exception { @Test public void test301removeUserFromAutoGroup() throws Exception { - final String TEST_NAME = "test301removeUserFromAutoGroup"; - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); // GIVEN @@ -292,8 +280,6 @@ public void test301removeUserFromAutoGroup() throws Exception { @Test public void test402assignAutoGroupDirectly() throws Exception { - final String TEST_NAME = "test402assignAutoGroupDirectly"; - DummyGroup craticGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_CRATIC_NAME); craticGroup.removeMember(USER_HERMAN_USERNAME); @@ -328,8 +314,6 @@ public void test402assignAutoGroupDirectly() throws Exception { @Test public void test403removeAllAssignments() throws Exception { - final String TEST_NAME = "test403removeAllAssignments"; - DummyGroup testersGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_TESTERS_NAME); testersGroup.removeMember(USER_HERMAN_USERNAME); @@ -356,8 +340,6 @@ public void test403removeAllAssignments() throws Exception { @Test public void test404importAssociationAutotesters() throws Exception { - final String TEST_NAME = "test404importAssociationAutotesters"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.FULL, true); DummyGroup craticGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_CRATIC_NAME); @@ -393,8 +375,6 @@ public void test404importAssociationAutotesters() throws Exception { @Test public void test405assignRoleAutocraticDirectly() throws Exception { - final String TEST_NAME = "test405assignRoleAutocraticDirectly"; - assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); // GIVEN Task task = getTestTask(); @@ -420,8 +400,6 @@ public void test405assignRoleAutocraticDirectly() throws Exception { @Test public void test406unassignRoleAutocraticDirectly() throws Exception { - final String TEST_NAME = "test406unassignRoleAutocraticAutotestersDirectly"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.FULL, true); // GIVEN @@ -448,8 +426,6 @@ public void test406unassignRoleAutocraticDirectly() throws Exception { @Test public void test407addHermanToTestersReconcile() throws Exception { - final String TEST_NAME = "test407addHermanToTestersReconcile"; - assumeResourceAssigmentPolicy(RESOURCE_DUMMY_AUTOGREEN_OID, AssignmentPolicyEnforcementType.FULL, true); DummyGroup craticGroup = getDummyResource(RESOURCE_DUMMY_AUTOGREEN_NAME).getGroupByName(GROUP_DUMMY_CRATIC_NAME); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java index f991e41a4ef..fb0ee822279 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMappingInbound.java @@ -6,6 +6,20 @@ */ package com.evolveum.midpoint.model.intest.mapping; +import static java.util.Collections.singleton; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import java.io.FileNotFoundException; +import java.nio.charset.StandardCharsets; +import javax.xml.namespace.QName; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.icf.dummy.resource.DummySyncStyle; import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; @@ -26,29 +40,13 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import java.io.File; -import java.io.FileNotFoundException; -import java.nio.charset.StandardCharsets; - -import javax.xml.namespace.QName; - -import static java.util.Collections.singleton; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; - /** * Tests inbound mappings. Uses live sync to do that. * These tests are much simpler and more focused than those in AbstractSynchronizationStoryTest. * * @author mederly - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMappingInbound extends AbstractMappingTest { @@ -81,7 +79,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti controller.extendSchemaPirate(); controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(), DUMMY_ACCOUNT_ATTRIBUTE_LOCKER_NAME, String.class, false, false) - .setSensitive(true); + .setSensitive(true); controller.addAttrDef(controller.getDummyResource().getAccountObjectClass(), DUMMY_ACCOUNT_ATTRIBUTE_PROOF_NAME, String.class, false, false); controller.setSyncStyle(DummySyncStyle.SMART); @@ -91,8 +89,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010SanitySchema() throws Exception { - final String TEST_NAME = "test010SanitySchema"; - // GIVEN Task task = getTestTask(); @@ -118,26 +114,15 @@ public void test010SanitySchema() throws Exception { @Test public void test100ImportLiveSyncTaskDummyTeaGreen() throws Exception { - final String TEST_NAME = "test100ImportLiveSyncTaskDummyTeaGreen"; - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); importSyncTask(); - // THEN then(); - waitForSyncTaskStart(); } @Test public void test110AddDummyTeaGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test110AddDummyTeaGreenAccountMancomb"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -171,19 +156,19 @@ public void test110AddDummyTeaGreenAccountMancomb() throws Exception { UserAsserter mancombUserAsserter = assertUserAfterByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME); mancombLocker = mancombUserAsserter - .links() + .links() .single() - .assertOid(accountMancomb.getOid()) - .end() + .assertOid(accountMancomb.getOid()) .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .extension() + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .extension() .property(PIRACY_LOCKER) - .singleValue() - .protectedString() - .assertIsEncrypted() - .assertCompareCleartext(LOCKER_BIG_SECRET) - .getProtectedString(); + .singleValue() + .protectedString() + .assertIsEncrypted() + .assertCompareCleartext(LOCKER_BIG_SECRET) + .getProtectedString(); assertJpegPhoto(UserType.class, mancombUserAsserter.getOid(), "water".getBytes(StandardCharsets.UTF_8), result); // assertUsers(6); @@ -197,8 +182,6 @@ public void test110AddDummyTeaGreenAccountMancomb() throws Exception { */ @Test public void test120ModifyMancombPhotoSource() throws Exception { - final String TEST_NAME = "test120ModifyMancombPhotoSource"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -232,8 +215,6 @@ public void test120ModifyMancombPhotoSource() throws Exception { */ @Test public void test130ModifyMancombPhotoSourceAndReconcile() throws Exception { - final String TEST_NAME = "test130ModifyMancombPhotoSourceAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -271,8 +252,6 @@ public void test130ModifyMancombPhotoSourceAndReconcile() throws Exception { */ @Test public void test140ModifyMancombPhotoInRepo() throws Exception { - final String TEST_NAME = "test140ModifyMancombPhotoInRepo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -307,8 +286,6 @@ public void test140ModifyMancombPhotoInRepo() throws Exception { */ @Test public void test150UserReconcile() throws Exception { - final String TEST_NAME = "test150UserReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -336,23 +313,23 @@ public void test150UserReconcile() throws Exception { assertShadowOperationalData(accountMancomb, SynchronizationSituationType.LINKED, null); assertUserAfterByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME) - .links() + .links() .single() - .assertOid(accountMancomb.getOid()) - .end() + .assertOid(accountMancomb.getOid()) + .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .extension() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .extension() .property(PIRACY_LOCKER) - .singleValue() - .protectedString() - .assertIsEncrypted() - .assertCompareCleartext(LOCKER_BIG_SECRET) - // Make sure that this is exactly the same content of protected string - // including all the randomized things (IV). If it is the same, - // there is a good chance we haven't had any phantom changes - // MID-5197 - .assertEquals(mancombLocker); + .singleValue() + .protectedString() + .assertIsEncrypted() + .assertCompareCleartext(LOCKER_BIG_SECRET) + // Make sure that this is exactly the same content of protected string + // including all the randomized things (IV). If it is the same, + // there is a good chance we haven't had any phantom changes + // MID-5197 + .assertEquals(mancombLocker); // assertUsers(6); @@ -365,13 +342,6 @@ public void test150UserReconcile() throws Exception { @Test public void test300DeleteDummyTeaGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test300DeleteDummyTeaGreenAccountMancomb"; - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - /// WHEN when(); getDummyResource(RESOURCE_DUMMY_TEA_GREEN_NAME).deleteAccountByName(ACCOUNT_MANCOMB_DUMMY_USERNAME); @@ -387,12 +357,12 @@ public void test300DeleteDummyTeaGreenAccountMancomb() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_TEA_GREEN_NAME, ACCOUNT_MANCOMB_DUMMY_USERNAME); assertUserAfterByUsername(ACCOUNT_MANCOMB_DUMMY_USERNAME) - .assertFullName("Mancomb Seepgood") - .links() + .assertFullName("Mancomb Seepgood") + .links() .single() - .resolveTarget() - .assertTombstone() - .assertSynchronizationSituation(SynchronizationSituationType.DELETED); + .resolveTarget() + .assertTombstone() + .assertSynchronizationSituation(SynchronizationSituationType.DELETED); // assertUsers(7 + getNumberOfExtraDummyUsers()); @@ -403,8 +373,6 @@ public void test300DeleteDummyTeaGreenAccountMancomb() throws Exception { // Remove livesync task so it won't get into the way for next tests @Test public void test399DeleteDummyTeaGreenAccountMancomb() throws Exception { - final String TEST_NAME = "test399DeleteDummyTeaGreenAccountMancomb"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -421,8 +389,6 @@ public void test399DeleteDummyTeaGreenAccountMancomb() throws Exception { @Test public void test400AddUserLeeloo() throws Exception { - final String TEST_NAME = "test400AddUserLeeloo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -449,13 +415,13 @@ public void test400AddUserLeeloo() throws Exception { then(); userLeelooOid = assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED) - .getOid(); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED) + .getOid(); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -474,8 +440,6 @@ public void test400AddUserLeeloo() throws Exception { */ @Test public void test402UserLeelooRecompute() throws Exception { - final String TEST_NAME = "test402UserLeelooRecompute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -490,12 +454,12 @@ public void test402UserLeelooRecompute() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(0); @@ -507,8 +471,6 @@ public void test402UserLeelooRecompute() throws Exception { */ @Test public void test404UserLeelooReconcile() throws Exception { - final String TEST_NAME = "test404UserLeelooReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -523,12 +485,12 @@ public void test404UserLeelooReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_MULTIPASS) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -544,8 +506,6 @@ public void test404UserLeelooReconcile() throws Exception { */ @Test public void test410UserLeeloominaiReconcile() throws Exception { - final String TEST_NAME = "test410UserLeeloominaiReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -564,12 +524,12 @@ public void test410UserLeeloominaiReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -586,8 +546,6 @@ public void test410UserLeeloominaiReconcile() throws Exception { */ @Test public void test412UserLeeloominaiRecompute() throws Exception { - final String TEST_NAME = "test412UserLeeloominaiRecompute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -602,12 +560,12 @@ public void test412UserLeeloominaiRecompute() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(0); @@ -619,8 +577,6 @@ public void test412UserLeeloominaiRecompute() throws Exception { */ @Test public void test414UserLeeloominaiReconcile() throws Exception { - final String TEST_NAME = "test414UserLeeloominaiReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -635,12 +591,12 @@ public void test414UserLeeloominaiReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -656,8 +612,6 @@ public void test414UserLeeloominaiReconcile() throws Exception { */ @Test public void test420UserLeelooStrangeReconcile() throws Exception { - final String TEST_NAME = "test420UserLeelooStrangeReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -676,13 +630,13 @@ public void test420UserLeelooStrangeReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); @@ -699,8 +653,6 @@ public void test420UserLeelooStrangeReconcile() throws Exception { */ @Test public void test424UserLeelooStrangeReconcile() throws Exception { - final String TEST_NAME = "test424UserLeelooStrangeReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -715,13 +667,13 @@ public void test424UserLeelooStrangeReconcile() throws Exception { then(); assertUserAfterByUsername(ACCOUNT_LEELOO_USERNAME) - .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) - .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) - .links() + .assertFullName(ACCOUNT_LEELOO_FULL_NAME_LEELOOMINAI) + .assertDescription(ACCOUNT_LEELOO_PROOF_STRANGE) + .links() .single() - .end() .end() - .assertAdministrativeStatus(ActivationStatusType.ENABLED); + .end() + .assertAdministrativeStatus(ActivationStatusType.ENABLED); display("Audit", dummyAuditService); dummyAuditService.assertRecords(2); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java index 482e0c5684a..75b872f0fc7 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMigration.java @@ -6,8 +6,6 @@ */ package com.evolveum.midpoint.model.intest.misc; -import static org.testng.AssertJUnit.assertEquals; - import java.io.File; import org.springframework.test.annotation.DirtiesContext; @@ -58,8 +56,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test050SanityLost1() throws Exception { - final String TEST_NAME = "test050SanityLost1"; - // WHEN when(); PrismObject shadowLost1Repo = getShadowRepo(SHADOW_ACCOUNT_DUMMY_LOST1_OID); @@ -77,8 +73,6 @@ public void test050SanityLost1() throws Exception { */ @Test public void test100RefreshTaskDefault() throws Exception { - final String TEST_NAME = "test100RefreshTaskDefault"; - addObject(TASK_SHADOW_REFRESH_FILE); // WHEN @@ -101,8 +95,6 @@ public void test100RefreshTaskDefault() throws Exception { */ @Test public void test110RefreshTaskExplicitDummy() throws Exception { - final String TEST_NAME = "test110RefreshTaskExplicitDummy"; - addObject(TASK_SHADOW_REFRESH_EXPLICIT_DUMMY_FILE); // WHEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java index 0afde18db71..b6c3e330dff 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestMisc.java @@ -6,22 +6,15 @@ */ package com.evolveum.midpoint.model.intest.misc; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertEquals; +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.List; - import javax.xml.transform.dom.DOMSource; import javax.xml.validation.Schema; import javax.xml.validation.Validator; -import com.evolveum.midpoint.prism.PrismContext; - -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.util.exception.SystemException; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -30,8 +23,10 @@ import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.Objectable; +import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismReference; +import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.RepositoryDiag; @@ -43,17 +38,10 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RelationDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -/** - * @author semancik - * - */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +import com.evolveum.midpoint.util.exception.SystemException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMisc extends AbstractInitializedModelIntegrationTest { @@ -90,9 +78,7 @@ public void initSystem(Task initTask, OperationResult initResult) } @Test - public void test100GetRepositoryDiag() throws Exception { - final String TEST_NAME = "test100GetRepositoryDiag"; - + public void test100GetRepositoryDiag() { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -112,9 +98,7 @@ public void test100GetRepositoryDiag() throws Exception { } @Test - public void test110RepositorySelfTest() throws Exception { - final String TEST_NAME = "test110RepositorySelfTest"; - + public void test110RepositorySelfTest() { // GIVEN Task task = getTestTask(); @@ -132,8 +116,6 @@ public void test110RepositorySelfTest() throws Exception { @Test public void test200ExportUsers() throws Exception { - final String TEST_NAME = "test200ExportUsers"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -148,9 +130,9 @@ public void test200ExportUsers() throws Exception { assertSuccess(result); assertEquals("Unexpected number of users", 6, users.size()); - for (PrismObject user: users) { + for (PrismObject user : users) { display("Exporting user", user); - assertNotNull("Null definition in "+user, user.getDefinition()); + assertNotNull("Null definition in " + user, user.getDefinition()); display("Definition", user.getDefinition()); String xmlString = prismContext.serializerFor(PrismContext.LANG_XML).serialize(user); display("Exported user", xmlString); @@ -162,10 +144,8 @@ public void test200ExportUsers() throws Exception { validator.validate(new DOMSource(xmlDocument)); PrismObject parsedUser = prismContext.parseObject(xmlString); - assertTrue("Re-parsed user is not equal to original: "+user, user.equals(parsedUser)); - + assertEquals("Re-parsed user is not equal to original: " + user, parsedUser, user); } - } /** @@ -174,21 +154,19 @@ public void test200ExportUsers() throws Exception { */ @Test public void test210SearchUsersMatchingRulesPolystringNorm() throws Exception { - final String TEST_NAME = "test210SearchUsersMatchingRulesPolystringNorm"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = queryFor(UserType.class) .item(UserType.F_NAME) - .eq("JacK") - .matchingNorm() + .eq("JacK") + .matchingNorm() .build(); // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query,null , task, result); + List> users = modelService.searchObjects(UserType.class, query, null, task, result); // THEN then(); @@ -207,8 +185,6 @@ public void test210SearchUsersMatchingRulesPolystringNorm() throws Exception { */ @Test public void test212SearchUsersMatchingRulesPolystringIgnoreCase() throws Exception { - final String TEST_NAME = "test212SearchUsersMatchingRulesPolystringIgnoreCase"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -222,8 +198,7 @@ public void test212SearchUsersMatchingRulesPolystringIgnoreCase() throws Excepti try { // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query, null, task, result); - + modelService.searchObjects(UserType.class, query, null, task, result); } catch (SystemException e) { // this is expected } @@ -236,8 +211,6 @@ public void test212SearchUsersMatchingRulesPolystringIgnoreCase() throws Excepti */ @Test public void test214SearchUsersMatchingRulesStringIgnoreCase() throws Exception { - final String TEST_NAME = "test214SearchUsersMatchingRulesStringIgnoreCase"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -250,7 +223,7 @@ public void test214SearchUsersMatchingRulesStringIgnoreCase() throws Exception { // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query,null , task, result); + List> users = modelService.searchObjects(UserType.class, query, null, task, result); // THEN then(); @@ -269,8 +242,6 @@ public void test214SearchUsersMatchingRulesStringIgnoreCase() throws Exception { */ @Test public void test216SearchUsersMatchingRulesStringNorm() throws Exception { - final String TEST_NAME = "test216SearchUsersMatchingRulesStringNorm"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -283,7 +254,7 @@ public void test216SearchUsersMatchingRulesStringNorm() throws Exception { // WHEN when(); - List> users = modelService.searchObjects(UserType.class, query,null , task, result); + List> users = modelService.searchObjects(UserType.class, query, null, task, result); // THEN then(); @@ -298,8 +269,6 @@ public void test216SearchUsersMatchingRulesStringNorm() throws Exception { */ @Test public void test300RecomputeJack() throws Exception { - final String TEST_NAME = "test300RecomputeJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -322,8 +291,6 @@ public void test300RecomputeJack() throws Exception { */ @Test public void test302UpdateKeyJack() throws Exception { - final String TEST_NAME = "test302UpdateKeyJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -343,8 +310,6 @@ public void test302UpdateKeyJack() throws Exception { @Test public void test310AddUserClean() throws Exception { - final String TEST_NAME = "test310AddUserClean"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -371,8 +336,6 @@ public void test310AddUserClean() throws Exception { */ @Test public void test312UpdateBinaryIdClean() throws Exception { - final String TEST_NAME = "test312UpdateBinaryIdClean"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -394,19 +357,14 @@ public void test312UpdateBinaryIdClean() throws Exception { * MID-4660, MID-4491, MID-3581 */ @Test - public void test320DefaultRelations() throws Exception { - final String TEST_NAME="test320DefaultRelations"; - - Task task = getTestTask(); - OperationResult result = task.getResult(); - + public void test320DefaultRelations() { // WHEN when(); List relations = modelInteractionService.getRelationDefinitions(); // THEN - then(); - display("Relations", relations); + then(); + display("Relations", relations); assertRelationDef(relations, SchemaConstants.ORG_MANAGER, "RelationTypes.manager"); assertRelationDef(relations, SchemaConstants.ORG_OWNER, "RelationTypes.owner"); assertEquals("Unexpected number of relation definitions", 7, relations.size()); @@ -417,8 +375,6 @@ public void test320DefaultRelations() throws Exception { */ @Test public void test400ImportRoleWithFilters() throws Exception { - final String TEST_NAME = "test400ImportRoleWithFilters"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -441,8 +397,6 @@ public void test400ImportRoleWithFilters() throws Exception { @Test public void test500AddHocProvisioningScriptAssignJackResourceScripty() throws Exception { - final String TEST_NAME = "test500AddHocProvisioningScriptAssignJackResourceScripty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -474,8 +428,6 @@ public void test500AddHocProvisioningScriptAssignJackResourceScripty() throws Ex */ @Test public void test502GetAccountJackResourceScripty() throws Exception { - final String TEST_NAME = "test502GetAccountJackResourceScripty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -506,8 +458,6 @@ public void test502GetAccountJackResourceScripty() throws Exception { */ @Test public void test504GetAccountJackResourceScriptyAgain() throws Exception { - final String TEST_NAME = "test504GetAccountJackResourceScriptyAgain"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -543,8 +493,6 @@ public void test504GetAccountJackResourceScriptyAgain() throws Exception { */ @Test public void test506ModifyResourceGetAccountJackResourceScripty() throws Exception { - final String TEST_NAME = "test506ModifyResourceGetAccountJackResourceScripty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -567,33 +515,26 @@ public void test506ModifyResourceGetAccountJackResourceScripty() throws Exceptio PrismObject resourceAfter = getObject(ResourceType.class, RESOURCE_SCRIPTY_OID); display("Resource version after", resourceAfter.getVersion()); - assertFalse("Resource version is still the same: "+resourceAfter.getVersion(), resourceBefore.getVersion().equals(resourceAfter.getVersion())); + assertThat(resourceAfter.getVersion()) + .withFailMessage("Resource version is still the same") + .isNotEqualTo(resourceBefore.getVersion()); PrismObject accountShadow = modelService.getObject(ShadowType.class, accountOid, null, task, result); Integer dummyConnectorNumber = ShadowUtil.getAttributeValue(accountShadow, getDummyResourceController(RESOURCE_DUMMY_SCRIPTY_NAME).getAttributeQName(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_WEALTH_NAME)); - assertTrue("Connector number hash changed: "+lastDummyConnectorNumber+" -> "+dummyConnectorNumber, - lastDummyConnectorNumber.equals(dummyConnectorNumber)); + assertEquals("Connector number hash changed: " + lastDummyConnectorNumber + " -> " + dummyConnectorNumber, + dummyConnectorNumber, lastDummyConnectorNumber); } - - /** * MID-4504 * midpoint.getLinkedShadow fails recomputing without throwing exception during shadow delete - * + *

* the ship attribute in the role "Ship" has mapping with calling midpoint.getLinkedShadow() on the reosurce which doesn't exist */ @Test public void test600jackAssignRoleShip() throws Exception { - final String TEST_NAME = "test600jackAssignRoleShip"; - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN when(); assignRole(USER_JACK_OID, ROLE_SHIP_OID); @@ -606,7 +547,7 @@ public void test600jackAssignRoleShip() throws Exception { assertLinks(userAfter, 1); PrismReference linkRef = userAfter.findReference(UserType.F_LINK_REF); - assertTrue(!linkRef.isEmpty()); + assertFalse(linkRef.isEmpty()); // PrismObject shadowModel = getShadowModel(linkRef.getOid()); @@ -616,11 +557,7 @@ public void test600jackAssignRoleShip() throws Exception { @Test public void test601jackUnassignResourceAccount() throws Exception { - final String TEST_NAME = "test601jackUnassignResourceAccount"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); display("User before", userBefore); assertAssignments(userBefore, 2); @@ -637,33 +574,22 @@ public void test601jackUnassignResourceAccount() throws Exception { assertLinks(userAfter, 1); } - /** * MID-4504 * midpoint.getLinkedShadow fails recomputing without throwing exception during shadow delete - * + *

* first assign role ship, the ship attribute in the role has mapping with calling midpoint.getLinkedShadow() */ @Test public void test602jackUnssigndRoleShip() throws Exception { - final String TEST_NAME = "test602jackUnssigndRoleShip"; - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - - // WHEN when(); unassignRole(USER_JACK_OID, ROLE_SHIP_OID); - //THEN then(); PrismObject userAfter = getUser(USER_JACK_OID); display("User before", userAfter); assertAssignments(userAfter, 0); assertLinks(userAfter, 0); - } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestUuidNonUniqueName.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestUuidNonUniqueName.java index a29f8f769d0..a35d9613d92 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestUuidNonUniqueName.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/misc/TestUuidNonUniqueName.java @@ -6,9 +6,7 @@ */ package com.evolveum.midpoint.model.intest.misc; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertNotNull; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.AssertJUnit.assertEquals; import java.io.File; @@ -33,7 +31,7 @@ * * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUuidNonUniqueName extends AbstractInitializedModelIntegrationTest { @@ -51,23 +49,21 @@ public class TestUuidNonUniqueName extends AbstractInitializedModelIntegrationTe protected static final String USER_SKELLINGTON_FULL_NAME = "Jack Skellington"; String accountJackSparrowUid; - String accountJackSkellingtonUid; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - initDummyResourcePirate(RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_NAME, - RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_FILE, RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_OID, initTask, initResult); + initDummyResourcePirate( + RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_NAME, RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_FILE, + RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_OID, initTask, initResult); importObjectFromFile(USER_SKELLINGTON_FILE); } @Test public void test010TestResourceConnection() throws Exception { - final String TEST_NAME = "test010TestResourceConnection"; - // GIVEN Task task = getTestTask(); @@ -80,14 +76,12 @@ public void test010TestResourceConnection() throws Exception { assertSuccess(result); assertResourceAfter(RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_OID) - .displayXml() - .assertHasSchema(); + .displayXml() + .assertHasSchema(); } @Test public void test020RefinedSchema() throws Exception { - final String TEST_NAME = "test020RefinedSchema"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -101,9 +95,10 @@ public void test020RefinedSchema() throws Exception { assertSuccess(result); assertResourceAfter(RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_OID) - .displayXml() - .assertHasSchema(); + .displayXml() + .assertHasSchema(); + // @formatter:off assertRefinedResourceSchema(resource, "after") .assertNamespace(MidPointConstants.NS_RI) .defaultAccountDefinition() @@ -115,13 +110,11 @@ public void test020RefinedSchema() throws Exception { .assertNotPrimaryIdentifier() .assertNotSecondaryIdentifier() .end(); - + // @formatter:on } @Test public void test100AssignAccountToJackSparrow() throws Exception { - final String TEST_NAME = "test100AssignAccountToJackSparrow"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -134,6 +127,7 @@ public void test100AssignAccountToJackSparrow() throws Exception { then(); assertSuccess(result); + // @formatter:off accountJackSparrowUid = assertUserAfter(USER_JACK_OID) .singleLink() .target() @@ -141,26 +135,26 @@ public void test100AssignAccountToJackSparrow() throws Exception { .attributes() .assertValue(SchemaConstants.ICFS_NAME, USER_JACK_GIVEN_NAME) .getValue(SchemaConstants.ICFS_UID); + // @formatter:on assertDummyAccountById(RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_NAME, accountJackSparrowUid) - .assertName(USER_JACK_GIVEN_NAME) - .assertId(accountJackSparrowUid) - .assertFullName(USER_JACK_FULL_NAME); + .assertName(USER_JACK_GIVEN_NAME) + .assertId(accountJackSparrowUid) + .assertFullName(USER_JACK_FULL_NAME); - assertFalse("Same sparrow's name and uid", USER_JACK_GIVEN_NAME.equals(accountJackSparrowUid)); + assertThat(accountJackSparrowUid).withFailMessage("Same sparrow's name and uid") + .isNotEqualTo(USER_JACK_GIVEN_NAME); } @Test public void test102GetAccountJackSparrow() throws Exception { - final String TEST_NAME = "test102GetAccountJackSparrow"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); String accountJackSparrowOid = assertUserBefore(USER_JACK_OID) .singleLink() - .getOid(); + .getOid(); // WHEN when(); @@ -170,13 +164,15 @@ public void test102GetAccountJackSparrow() throws Exception { then(); assertSuccess(result); + // @formatter:off assertShadow(shadow, "getObject") - .assertName(USER_JACK_GIVEN_NAME) - .attributes() - .assertValue(SchemaConstants.ICFS_NAME, USER_JACK_GIVEN_NAME) - .assertValue(SchemaConstants.ICFS_UID, accountJackSparrowUid) - .assertHasPrimaryIdentifier() - .assertNoSecondaryIdentifier(); + .assertName(USER_JACK_GIVEN_NAME) + .attributes() + .assertValue(SchemaConstants.ICFS_NAME, USER_JACK_GIVEN_NAME) + .assertValue(SchemaConstants.ICFS_UID, accountJackSparrowUid) + .assertHasPrimaryIdentifier() + .assertNoSecondaryIdentifier(); + // @formatter:on } /** @@ -184,8 +180,6 @@ public void test102GetAccountJackSparrow() throws Exception { */ @Test public void test110AssignAccountToJackSkellington() throws Exception { - final String TEST_NAME = "test110AssignAccountToJackSkellington"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -200,21 +194,24 @@ public void test110AssignAccountToJackSkellington() throws Exception { then(); assertSuccess(result); - accountJackSkellingtonUid = assertUserAfter(USER_SKELLINGTON_OID) + // @formatter:off + String accountJackSkellingtonUid = assertUserAfter(USER_SKELLINGTON_OID) .singleLink() .target() .assertName(USER_SKELLINGTON_GIVEN_NAME) .attributes() .assertValue(SchemaConstants.ICFS_NAME, USER_SKELLINGTON_GIVEN_NAME) .getValue(SchemaConstants.ICFS_UID); + // @formatter:on assertDummyAccountById(RESOURCE_DUMMY_UUID_NONUNIQUE_NAME_NAME, accountJackSkellingtonUid) - .assertName(USER_SKELLINGTON_GIVEN_NAME) - .assertId(accountJackSkellingtonUid) - .assertFullName(USER_SKELLINGTON_FULL_NAME); - - assertFalse("Same skellington's name and uid", USER_SKELLINGTON_GIVEN_NAME.equals(accountJackSkellingtonUid)); - assertFalse("Same skellington's and sparow's uid", accountJackSparrowUid.equals(accountJackSkellingtonUid)); + .assertName(USER_SKELLINGTON_GIVEN_NAME) + .assertId(accountJackSkellingtonUid) + .assertFullName(USER_SKELLINGTON_FULL_NAME); + + assertThat(accountJackSkellingtonUid).withFailMessage("Same skellington's name and uid") + .isNotEqualTo(USER_SKELLINGTON_GIVEN_NAME); + assertThat(accountJackSkellingtonUid).withFailMessage("Same skellington's and sparow's uid") + .isNotEqualTo(accountJackSparrowUid); } - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java index aac4c28f7c7..732c48e3cee 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java @@ -6,21 +6,16 @@ */ package com.evolveum.midpoint.model.intest.negative; -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 static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.*; + import static com.evolveum.midpoint.test.IntegrationTestTools.assertNoRepoCache; -import static org.testng.AssertJUnit.assertNotNull; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; -import com.evolveum.midpoint.prism.delta.DeltaFactory; import org.apache.commons.lang.StringUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -32,10 +27,12 @@ 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.model.impl.lens.LensContext; import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ChangeType; +import com.evolveum.midpoint.prism.delta.DeltaFactory; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.provisioning.api.GenericConnectorException; import com.evolveum.midpoint.schema.ObjectDeltaOperation; @@ -45,19 +42,7 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; /** @@ -65,15 +50,11 @@ * correct handling of connector exceptions. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestAssignmentErrors extends AbstractInitializedModelIntegrationTest { - private static final String TEST_DIR = "src/test/resources/negative"; - private static final String TEST_TARGET_DIR = "target/test/negative"; - private static final String USER_LEMONHEAD_NAME = "lemonhead"; private static final String USER_LEMONHEAD_FULLNAME = "Lemonhead"; private static final String USER_SHARPTOOTH_NAME = "sharptooth"; @@ -81,8 +62,6 @@ public class TestAssignmentErrors extends AbstractInitializedModelIntegrationTes private static final String USER_SHARPTOOTH_PASSWORD_1_CLEAR = "SHARPyourT33TH"; private static final String USER_SHARPTOOTH_PASSWORD_2_CLEAR = "L00SEyourT33TH"; private static final String USER_SHARPTOOTH_PASSWORD_3_CLEAR = "HAV3noT33TH"; - private static final String USER_REDSKULL_NAME = "redskull"; - private static final String USER_REDSKULL_FULLNAME = "Red Skull"; private static final String USER_AFET_NAME = "afet"; private static final String USER_AFET_FULLNAME = "Alfredo Fettucini"; @@ -91,10 +70,6 @@ public class TestAssignmentErrors extends AbstractInitializedModelIntegrationTes private static final String USER_CFET_NAME = "cfet"; private static final String USER_CFET_FULLNAME = "Carlos Fettucini"; - protected static final Trace LOGGER = TraceManager.getTrace(TestAssignmentErrors.class); - - private PrismObject resource; - private String userLemonheadOid; private String userSharptoothOid; @Override @@ -162,8 +137,6 @@ public void test010RefinedSchemaWhite() throws Exception { */ @Test public void test100UserJackAssignBlankAccount() throws Exception { - final String TEST_NAME = "test100UserJackAssignBlankAccount"; - // GIVEN Task task = getTestTask(); @@ -204,8 +177,6 @@ public void test100UserJackAssignBlankAccount() throws Exception { */ @Test public void test101AddUserCharlesAssignBlankAccount() throws Exception { - final String TEST_NAME = "test101AddUserCharlesAssignBlankAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -243,11 +214,8 @@ public void test101AddUserCharlesAssignBlankAccount() throws Exception { } - @Test public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { - final String TEST_NAME = "test200UserLemonheadAssignAccountBrokenNetwork"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -255,7 +223,6 @@ public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { PrismObject user = createUser(USER_LEMONHEAD_NAME, USER_LEMONHEAD_FULLNAME); addObject(user); - userLemonheadOid = user.getOid(); Collection> deltas = new ArrayList<>(); ObjectDelta accountAssignmentUserDelta = createAccountAssignmentUserDelta(user.getOid(), RESOURCE_DUMMY_OID, null, true); @@ -290,11 +257,8 @@ public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { // TODO: timeout or explicit retry // @Test // public void test205UserLemonheadRecovery() throws Exception { -// final String TEST_NAME = "test205UserLemonheadRecovery"; -// TestUtil.displayTestTile(this, TEST_NAME); -// // // GIVEN -// Task task = createTask(TEST_NAME); +// Task task = getTestTask(); // OperationResult result = task.getResult(); // assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); // @@ -324,8 +288,6 @@ public void test200UserLemonheadAssignAccountBrokenNetwork() throws Exception { @Test public void test210UserSharptoothAssignAccountBrokenGeneric() throws Exception { - final String TEST_NAME = "test210UserSharptoothAssignAccountBrokenGeneric"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -393,8 +355,6 @@ public void test210UserSharptoothAssignAccountBrokenGeneric() throws Exception { */ @Test public void test212UserSharptoothAssignAccountRecovery() throws Exception { - final String TEST_NAME = "test212UserSharptoothAssignAccountRecovery"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -424,25 +384,25 @@ public void test212UserSharptoothAssignAccountRecovery() throws Exception { */ @Test public void test214UserSharptoothChangePasswordNetworkError() throws Exception { - testUserSharptoothChangePasswordError("test214UserSharptoothChangePasswordNetworkError", + testUserSharptoothChangePasswordError( BreakMode.NETWORK, USER_SHARPTOOTH_PASSWORD_1_CLEAR, USER_SHARPTOOTH_PASSWORD_2_CLEAR, OperationResultStatus.IN_PROGRESS); } /** * Change user password. But there is generic error on the resource. - * + *

* Default dummy resource has no error criticality definition. Therefore generic errors * are considered critical. This operation is supposed to die. - * + *

* MID-3569 */ @Test public void test215UserSharptoothChangePasswordGenericError() throws Exception { try { - testUserSharptoothChangePasswordError("test215UserSharptoothChangePasswordGenericError", - BreakMode.GENERIC, USER_SHARPTOOTH_PASSWORD_1_CLEAR, USER_SHARPTOOTH_PASSWORD_3_CLEAR, - OperationResultStatus.FATAL_ERROR); + testUserSharptoothChangePasswordError( + BreakMode.GENERIC, USER_SHARPTOOTH_PASSWORD_1_CLEAR, USER_SHARPTOOTH_PASSWORD_3_CLEAR, + OperationResultStatus.FATAL_ERROR); assertNotReached(); } catch (GenericConnectorException e) { @@ -466,7 +426,9 @@ public void test215UserSharptoothChangePasswordGenericError() throws Exception { // OperationResultStatus.PARTIAL_ERROR); // } - public void testUserSharptoothChangePasswordError(final String TEST_NAME, BreakMode breakMode, String oldPassword, String newPassword, OperationResultStatus expectedResultStatus) throws Exception { + public void testUserSharptoothChangePasswordError(BreakMode breakMode, + String oldPassword, String newPassword, OperationResultStatus expectedResultStatus) + throws Exception { // GIVEN Task task = getTestTask(); @@ -498,15 +460,13 @@ public void testUserSharptoothChangePasswordError(final String TEST_NAME, BreakM /** * Assign account to user, delete the account shadow (not the account), recompute the user. * We expect that the shadow will be re-created and re-linked. - * + *

* This is tried on the default dummy resource where synchronization is enabled. */ @Test public void test220UserAssignAccountDeletedShadowRecomputeSync() throws Exception { - final String TEST_NAME = "test220UserAssignAccountDeletedShadowRecomputeSync"; - //GIVEN - PrismObject user = setupUserAssignAccountDeletedShadowRecompute(TEST_NAME, RESOURCE_DUMMY_OID, null, + PrismObject user = setupUserAssignAccountDeletedShadowRecompute(RESOURCE_DUMMY_OID, null, USER_AFET_NAME, USER_AFET_FULLNAME); String shadowOidBefore = getSingleLinkOid(user); Task task = getTestTask(); @@ -518,7 +478,7 @@ public void test220UserAssignAccountDeletedShadowRecomputeSync() throws Exceptio // THEN result.computeStatus(); display("Recompute result", result); - TestUtil.assertSuccess(result,2); + TestUtil.assertSuccess(result, 2); user = getUser(user.getOid()); display("User after", user); @@ -527,7 +487,9 @@ public void test220UserAssignAccountDeletedShadowRecomputeSync() throws Exceptio PrismObject shadowAfter = repositoryService.getObject(ShadowType.class, shadowOidAfter, null, result); display("Shadow after", shadowAfter); - assertFalse("New and old shadow OIDs are the same", shadowOidBefore.equals(shadowOidAfter)); + assertThat(shadowOidAfter) + .withFailMessage("New and old shadow OIDs are the same") + .isNotEqualTo(shadowOidBefore); // ... and again ... @@ -540,7 +502,7 @@ public void test220UserAssignAccountDeletedShadowRecomputeSync() throws Exceptio // THEN result.computeStatus(); display("Recompute result", result); - TestUtil.assertSuccess(result,2); + TestUtil.assertSuccess(result, 2); user = getUser(user.getOid()); display("User after", user); @@ -553,7 +515,7 @@ public void test220UserAssignAccountDeletedShadowRecomputeSync() throws Exceptio /** * Assign account to user, delete the account shadow (not the account), recompute the user. * We expect an error. - * + *

* This is tried on the red dummy resource where there is no synchronization. */ //TODO: after fixing uniqueness check in ProjectionValueProcessor, change the test little bit @@ -563,7 +525,7 @@ public void test222UserAssignAccountDeletedShadowRecomputeNoSync() throws Except final String TEST_NAME = "test222UserAssignAccountDeletedShadowRecomputeNoSync"; // GIVEN - PrismObject user = setupUserAssignAccountDeletedShadowRecompute(TEST_NAME, RESOURCE_DUMMY_RED_OID, + PrismObject user = setupUserAssignAccountDeletedShadowRecompute(RESOURCE_DUMMY_RED_OID, RESOURCE_DUMMY_RED_NAME, USER_BFET_NAME, USER_BFET_FULLNAME); Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); @@ -608,15 +570,13 @@ public void test222UserAssignAccountDeletedShadowRecomputeNoSync() throws Except /** * Assign account to user, delete the account shadow (not the account), recompute the user. * We expect that the shadow will be re-created and re-linked. - * + *

* This is tried on the yellow dummy resource where there is reduced synchronization config. */ @Test public void test224UserAssignAccountDeletedShadowRecomputeReducedSync() throws Exception { - final String TEST_NAME = "test224UserAssignAccountDeletedShadowRecomputeReducedSync"; - //GIVEN - PrismObject user = setupUserAssignAccountDeletedShadowRecompute(TEST_NAME, + PrismObject user = setupUserAssignAccountDeletedShadowRecompute( RESOURCE_DUMMY_YELLOW_OID, RESOURCE_DUMMY_YELLOW_NAME, USER_CFET_NAME, USER_CFET_FULLNAME); String shadowOidBefore = getSingleLinkOid(user); @@ -629,7 +589,7 @@ public void test224UserAssignAccountDeletedShadowRecomputeReducedSync() throws E // THEN result.computeStatus(); display("Recompute result", result); - TestUtil.assertSuccess(result,2); + TestUtil.assertSuccess(result, 2); user = getUser(user.getOid()); display("User after", user); @@ -638,7 +598,8 @@ public void test224UserAssignAccountDeletedShadowRecomputeReducedSync() throws E PrismObject shadowAfter = repositoryService.getObject(ShadowType.class, shadowOidAfter, null, result); display("Shadow after", shadowAfter); - assertFalse("New and old shadow OIDs are the same", shadowOidBefore.equals(shadowOidAfter)); + assertThat(shadowOidAfter).withFailMessage("New and old shadow OIDs are the same") + .isNotEqualTo(shadowOidBefore); // ... and again ... @@ -651,7 +612,7 @@ public void test224UserAssignAccountDeletedShadowRecomputeReducedSync() throws E // THEN result.computeStatus(); display("Recompute result", result); - TestUtil.assertSuccess(result,2); + TestUtil.assertSuccess(result, 2); user = getUser(user.getOid()); display("User after", user); @@ -662,8 +623,9 @@ public void test224UserAssignAccountDeletedShadowRecomputeReducedSync() throws E } - private PrismObject setupUserAssignAccountDeletedShadowRecompute(final String TEST_NAME, String dummyResourceOid, - String dummyResourceName, String userName, String userFullName) throws Exception { + private PrismObject setupUserAssignAccountDeletedShadowRecompute( + String dummyResourceOid, String dummyResourceName, String userName, String userFullName) + throws Exception { // GIVEN Task task = getTestTask(); @@ -703,6 +665,4 @@ private PrismObject setupUserAssignAccountDeletedShadowRecompute(final return user; } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java index b33fd62a8e9..2412846d90b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestBrokenResources.java @@ -6,18 +6,16 @@ */ package com.evolveum.midpoint.model.intest.negative; -import static com.evolveum.midpoint.test.asserter.predicate.TimeAssertionPredicates.approximatelyCurrent; -import static com.evolveum.midpoint.test.asserter.predicate.StringAssertionPredicates.startsWith; - +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; +import static com.evolveum.midpoint.test.asserter.predicate.StringAssertionPredicates.startsWith; +import static com.evolveum.midpoint.test.asserter.predicate.TimeAssertionPredicates.approximatelyCurrent; + import java.io.File; import java.util.Collection; -import com.evolveum.midpoint.prism.delta.DeltaFactory; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -29,6 +27,7 @@ import com.evolveum.icf.dummy.resource.DummyResource; import com.evolveum.midpoint.model.intest.AbstractConfiguredModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.DeltaFactory; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.provisioning.api.GenericConnectorException; @@ -36,7 +35,6 @@ import com.evolveum.midpoint.schema.ResultHandler; import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.internals.InternalCounters; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; @@ -46,30 +44,25 @@ import com.evolveum.midpoint.test.ProvisioningScriptSpec; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SystemException; +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.*; /** * Tests the model service contract by using a broken CSV resource. Tests for negative test cases, mostly * correct handling of connector exceptions. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestBrokenResources extends AbstractConfiguredModelIntegrationTest { private static final String TEST_DIR = "src/test/resources/negative"; private static final String TEST_TARGET_DIR = "target/test/negative"; - private static final File CONNECTOR_DUMMY_NOJARS_FILE = new File (TEST_DIR, "connector-dummy-nojars.xml"); - private static final String CONNECTOR_DUMMY_NOJARS_OID = "cccccccc-cccc-cccc-cccc-666600660004"; + private static final File CONNECTOR_DUMMY_NOJARS_FILE = new File(TEST_DIR, "connector-dummy-nojars.xml"); private static final File RESOURCE_CSVFILE_BROKEN_FILE = new File(TEST_DIR, "resource-csvfile-broken.xml"); private static final String RESOURCE_CSVFILE_BROKEN_OID = "ef2bc95b-76e0-48e2-86d6-3d4f02d3bbbb"; @@ -80,17 +73,17 @@ public class TestBrokenResources extends AbstractConfiguredModelIntegrationTest private static final File RESOURCE_DUMMY_NOJARS_FILE = new File(TEST_DIR, "resource-dummy-nojars.xml"); private static final String RESOURCE_DUMMY_NOJARS_OID = "10000000-0000-0000-0000-666600660004"; - private static final File RESOURCE_DUMMY_WRONG_CONNECTOR_OID_FILE = new File (TEST_DIR, "resource-dummy-wrong-connector-oid.xml"); + private static final File RESOURCE_DUMMY_WRONG_CONNECTOR_OID_FILE = new File(TEST_DIR, "resource-dummy-wrong-connector-oid.xml"); private static final String RESOURCE_DUMMY_WRONG_CONNECTOR_OID_OID = "10000000-0000-0000-0000-666600660005"; - private static final File RESOURCE_DUMMY_NO_CONFIGURATION_FILE = new File (TEST_DIR, "resource-dummy-no-configuration.xml"); + private static final File RESOURCE_DUMMY_NO_CONFIGURATION_FILE = new File(TEST_DIR, "resource-dummy-no-configuration.xml"); private static final String RESOURCE_DUMMY_NO_CONFIGURATION_OID = "10000000-0000-0000-0000-666600660006"; - private static final File RESOURCE_DUMMY_UNACCESSIBLE_FILE = new File (TEST_DIR, "resource-dummy-unaccessible.xml"); + private static final File RESOURCE_DUMMY_UNACCESSIBLE_FILE = new File(TEST_DIR, "resource-dummy-unaccessible.xml"); private static final String RESOURCE_DUMMY_UNACCESSIBLE_NAME = "unaccessible"; private static final String RESOURCE_DUMMY_UNACCESSIBLE_OID = "10000000-0000-0000-0000-666600660007"; - private static final File RESOURCE_DUMMY_EBONY_FILE = new File (TEST_DIR, "resource-dummy-ebony.xml"); + private static final File RESOURCE_DUMMY_EBONY_FILE = new File(TEST_DIR, "resource-dummy-ebony.xml"); private static final String RESOURCE_DUMMY_EBONY_NAME = "ebony"; private static final String RESOURCE_DUMMY_EBONY_OID = "10000000-0000-0000-0000-00000000e305"; @@ -98,12 +91,8 @@ public class TestBrokenResources extends AbstractConfiguredModelIntegrationTest protected static final File RESOURCE_DUMMY_BROKEN_VIOLET_FILE = new File(TEST_DIR, "resource-dummy-broken-violet.xml"); protected static final String RESOURCE_DUMMY_BROKEN_VIOLET_OID = "10000000-0000-0000-0000-0000000ba204"; protected static final String RESOURCE_DUMMY_BROKEN_VIOLET_NAME = "brokenViolet"; - protected static final String RESOURCE_DUMMY_BROKEN_VIOLET_NAMESPACE = MidPointConstants.NS_RI; - - private static final File ACCOUNT_SHADOW_JACK_CSVFILE_FILE = new File (TEST_DIR, "account-shadow-jack-csvfile.xml"); - private static final String ACCOUNT_SHADOW_JACK_CSVFILE_OID = "ef2bc95b-76e0-1111-d3ad-3d4f12120001"; - private static final File ACCOUNT_SHADOW_MURRAY_CSVFILE_FILE = new File (TEST_DIR, "account-shadow-murray-csvfile.xml"); + private static final File ACCOUNT_SHADOW_MURRAY_CSVFILE_FILE = new File(TEST_DIR, "account-shadow-murray-csvfile.xml"); private static final String ACCOUNT_SHADOW_MURRAY_CSVFILE_OID = "ef2bc95b-76e0-1111-d3ad-3d4f12120666"; private static final String BROKEN_CSV_FILE_NAME = "broken.csv"; @@ -122,7 +111,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Resources File targetDir = new File(TEST_TARGET_DIR); if (!targetDir.exists()) { - targetDir.mkdirs(); + assertThat(targetDir.mkdirs()).isTrue(); } MiscUtil.copyFile(new File(BROKEN_CSV_SOURCE_FILE_NAME), new File(BROKEN_CSV_TARGET_FILE_NAME)); @@ -162,24 +151,19 @@ public void postInitSystem(Task initTask, OperationResult initResult) throws Exc @Test public void test010TestResourceBroken() throws Exception { - final String TEST_NAME = "test010TestResourceBroken"; - - // GIVEN + given(); Task task = getTestTask(); - OperationResult result = task.getResult(); - // WHEN + when(); OperationResult testResult = modelService.testResource(RESOURCE_CSVFILE_BROKEN_OID, task); - // THEN + then(); display("testResource result", testResult); TestUtil.assertSuccess("testResource result", testResult); } @Test public void test020GetResourceBroken() throws Exception { - final String TEST_NAME = "test020GetResourceBroken"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -202,14 +186,11 @@ public void test020GetResourceBroken() throws Exception { @Test public void test030ListResources() throws Exception { - final String TEST_NAME = "test030ListResources"; - testListResources(TEST_NAME, NUMBER_OF_RESOURCES, null); + testListResources(NUMBER_OF_RESOURCES, null); } @Test public void test100GetAccountMurray() throws Exception { - final String TEST_NAME = "test100GetAccountMurray"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -234,8 +215,6 @@ public void test100GetAccountMurray() throws Exception { @Test public void test101GetAccountMurrayNoFetch() throws Exception { - final String TEST_NAME = "test101GetAccountMurrayNoFetch"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -275,7 +254,6 @@ public void test102GetAccountMurrayRaw() throws Exception { assertNotNull("Null resource", account); } - @Test public void test120SearchAccountByUsernameJack() throws Exception { @@ -286,9 +264,8 @@ public void test120SearchAccountByUsernameJack() throws Exception { PrismObject resource = modelService.getObject(ResourceType.class, RESOURCE_CSVFILE_BROKEN_OID, null, task, result); try { - // WHEN - PrismObject account = findAccountByUsername("jack", resource, task, result); + findAccountByUsername("jack", resource, task, result); AssertJUnit.fail("Expected SystemException but the operation was successful"); } catch (SystemException e) { @@ -297,16 +274,12 @@ public void test120SearchAccountByUsernameJack() throws Exception { display("findAccountByUsername result", result); TestUtil.assertFailure("findAccountByUsername result", result); } - } @Test public void test210TestResourceNotFound() throws Exception { - // GIVEN - Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + ".test210TestResourceNotFound"); - OperationResult result = task.getResult(); - + Task task = getTestTask(); // WHEN OperationResult testResult = modelService.testResource(RESOURCE_CSVFILE_NOTFOUND_OID, task); @@ -318,10 +291,8 @@ public void test210TestResourceNotFound() throws Exception { @Test public void test220GetResourceNotFound() throws Exception { - final String TEST_NAME = "test220GetResourceNotFound"; - // GIVEN - Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + "."+TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -332,19 +303,19 @@ public void test220GetResourceNotFound() throws Exception { assertResource(resource, "resource after") .display() .operationalState() - .assertAny() - .assertPropertyEquals(OperationalStateType.F_LAST_AVAILABILITY_STATUS, AvailabilityStatusType.BROKEN) - .assertPropertyEquals(OperationalStateType.F_NODE_ID, localNodeId) - .assertPropertyValueSatisfies(OperationalStateType.F_TIMESTAMP, approximatelyCurrent(60000)) - .assertPropertyValueSatisfies(OperationalStateType.F_MESSAGE, startsWith("Status set to BROKEN")) + .assertAny() + .assertPropertyEquals(OperationalStateType.F_LAST_AVAILABILITY_STATUS, AvailabilityStatusType.BROKEN) + .assertPropertyEquals(OperationalStateType.F_NODE_ID, localNodeId) + .assertPropertyValueSatisfies(OperationalStateType.F_TIMESTAMP, approximatelyCurrent(60000)) + .assertPropertyValueSatisfies(OperationalStateType.F_MESSAGE, startsWith("Status set to BROKEN")) .end() .operationalStateHistory() - .assertSize(1) - .value(0) - .assertPropertyEquals(OperationalStateType.F_LAST_AVAILABILITY_STATUS, AvailabilityStatusType.BROKEN) - .assertPropertyEquals(OperationalStateType.F_NODE_ID, localNodeId) - .assertPropertyValueSatisfies(OperationalStateType.F_TIMESTAMP, approximatelyCurrent(60000)) - .assertPropertyValueSatisfies(OperationalStateType.F_MESSAGE, startsWith("Status set to BROKEN")); + .assertSize(1) + .value(0) + .assertPropertyEquals(OperationalStateType.F_LAST_AVAILABILITY_STATUS, AvailabilityStatusType.BROKEN) + .assertPropertyEquals(OperationalStateType.F_NODE_ID, localNodeId) + .assertPropertyValueSatisfies(OperationalStateType.F_TIMESTAMP, approximatelyCurrent(60000)) + .assertPropertyValueSatisfies(OperationalStateType.F_MESSAGE, startsWith("Status set to BROKEN")); result.computeStatus(); display("getObject result", result); @@ -360,10 +331,8 @@ public void test220GetResourceNotFound() throws Exception { @Test public void test221GetResourceNotFoundResolveConnector() throws Exception { - final String TEST_NAME = "test221GetResourceNotFoundResolveConnector"; - // GIVEN - Task task = taskManager.createTaskInstance(TestBrokenResources.class.getName() + "."+TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); Collection> options = getOperationOptionsBuilder() @@ -377,11 +346,11 @@ public void test221GetResourceNotFoundResolveConnector() throws Exception { display("getObject resource", resource); result.computeStatus(); display("getObject result", result); - assertEquals("Expected partial errror in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); + assertEquals("Expected partial error in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); OperationResultType fetchResult = resource.asObjectable().getFetchResult(); display("resource.fetchResult", fetchResult); - assertEquals("Expected partial errror in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); + assertEquals("Expected partial error in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); // TODO: better asserts assertNotNull("Null resource", resource); @@ -389,7 +358,6 @@ public void test221GetResourceNotFoundResolveConnector() throws Exception { assertNotNull("Connector was not resolved", resource.asObjectable().getConnectorRef().asReferenceValue().getObject()); } - @Test public void test310TestResourceNoJars() throws Exception { @@ -406,8 +374,6 @@ public void test310TestResourceNoJars() throws Exception { @Test public void test320GetResourceNoJars() throws Exception { - final String TEST_NAME = "test320GetResourceNoJars"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -419,11 +385,11 @@ public void test320GetResourceNoJars() throws Exception { display("getObject resource", resource); result.computeStatus(); display("getObject result", result); - assertEquals("Expected partial errror in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); + assertEquals("Expected partial error in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); OperationResultType fetchResult = resource.asObjectable().getFetchResult(); display("resource.fetchResult", fetchResult); - assertEquals("Expected partial errror in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); + assertEquals("Expected partial error in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); // TODO: better asserts assertNotNull("Null resource", resource); @@ -431,8 +397,6 @@ public void test320GetResourceNoJars() throws Exception { @Test public void test350AddResourceWrongConnectorOid() throws Exception { - final String TEST_NAME = "test350AddResourceWrongConnectorOid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -462,8 +426,6 @@ public void test350AddResourceWrongConnectorOid() throws Exception { */ @Test public void test352AddResourceWrongConnectorOidRaw() throws Exception { - final String TEST_NAME = "test352AddResourceWrongConnectorOidRaw"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -487,15 +449,12 @@ public void test352AddResourceWrongConnectorOidRaw() throws Exception { TestUtil.assertFailure(result); } - /** * Store directly to repo. This is not really a test, it is more like a hack to prepare * environment for next tests. */ @Test public void test355AddResourceWrongConnectorOidRepo() throws Exception { - final String TEST_NAME = "test355AddResourceWrongConnectorOidRepo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -512,8 +471,6 @@ public void test355AddResourceWrongConnectorOidRepo() throws Exception { @Test public void test358GetResourceWrongConnectorOid() throws Exception { - final String TEST_NAME = "test358GetResourceWrongConnectorOid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -525,11 +482,11 @@ public void test358GetResourceWrongConnectorOid() throws Exception { display("getObject resource", resource); result.computeStatus(); display("getObject result", result); - assertEquals("Expected partial errror in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); + assertEquals("Expected partial error in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); OperationResultType fetchResult = resource.asObjectable().getFetchResult(); display("resource.fetchResult", fetchResult); - assertEquals("Expected partial errror in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); + assertEquals("Expected partial error in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); // TODO: better asserts assertNotNull("Null resource", resource); @@ -537,8 +494,6 @@ public void test358GetResourceWrongConnectorOid() throws Exception { @Test public void test359DeleteResourceWrongConnectorOid() throws Exception { - final String TEST_NAME = "test359DeleteResourceWrongConnectorOid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -554,15 +509,13 @@ public void test359DeleteResourceWrongConnectorOid() throws Exception { // THEN result.computeStatus(); display("getObject result", result); - assertEquals("Expected partial errror in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); + assertEquals("Expected partial error in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); assertNoObject(ResourceType.class, RESOURCE_DUMMY_WRONG_CONNECTOR_OID_OID, task, result); } @Test public void test360AddResourceNoConfiguration() throws Exception { - final String TEST_NAME = "test360AddResourceNoConfiguration"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -584,8 +537,6 @@ public void test360AddResourceNoConfiguration() throws Exception { @Test public void test362GetResourceNoConfiguration() throws Exception { - final String TEST_NAME = "test362GetResourceNoConfiguration"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -597,11 +548,11 @@ public void test362GetResourceNoConfiguration() throws Exception { display("getObject resource", resource); result.computeStatus(); display("getObject result", result); - assertEquals("Expected partial errror in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); + assertEquals("Expected partial error in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); OperationResultType fetchResult = resource.asObjectable().getFetchResult(); display("resource.fetchResult", fetchResult); - assertEquals("Expected partial errror in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); + assertEquals("Expected partial error in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); // TODO: better asserts assertNotNull("Null resource", resource); @@ -609,14 +560,11 @@ public void test362GetResourceNoConfiguration() throws Exception { @Test public void test368ListResources() throws Exception { - final String TEST_NAME = "test368ListResources"; - testListResources(TEST_NAME, NUMBER_OF_RESOURCES + 1, null); + testListResources(NUMBER_OF_RESOURCES + 1, null); } @Test public void test369DeleteResourceNoConfiguration() throws Exception { - final String TEST_NAME = "test369DeleteResourceNoConfiguration"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -638,14 +586,11 @@ public void test369DeleteResourceNoConfiguration() throws Exception { @Test public void test370ListResources() throws Exception { - final String TEST_NAME = "test370ListResources"; - testListResources(TEST_NAME, NUMBER_OF_RESOURCES, null); + testListResources(NUMBER_OF_RESOURCES, null); } @Test - public void test371ImportUnaccessibleResource() throws Exception { - final String TEST_NAME = "test371ImportUnaccessibleResource"; - + public void test371ImportInaccessibleResource() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -663,9 +608,7 @@ public void test371ImportUnaccessibleResource() throws Exception { * MID-3509 */ @Test - public void test372GetUnaccessibleResourceNoFetch() throws Exception { - final String TEST_NAME = "test372GetUnaccessibleResourceNoFetch"; - + public void test372GetInaccessibleResourceNoFetch() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -699,15 +642,13 @@ public void test372GetUnaccessibleResourceNoFetch() throws Exception { */ @Test public void test374ListResourcesNoFetch() throws Exception { - final String TEST_NAME = "test374ListResourcesNoFetch"; - rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT); rememberCounter(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_INSTANCE_CONFIGURATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); rememberCounter(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT); - testListResources(TEST_NAME, NUMBER_OF_RESOURCES + 1, GetOperationOptions.createNoFetchCollection()); + testListResources(NUMBER_OF_RESOURCES + 1, GetOperationOptions.createNoFetchCollection()); assertCounterIncrement(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_INITIALIZATION_COUNT, 0); @@ -718,11 +659,12 @@ public void test374ListResourcesNoFetch() throws Exception { @Test public void test375ListResources() throws Exception { - final String TEST_NAME = "test375ListResources"; - testListResources(TEST_NAME, NUMBER_OF_RESOURCES + 1, null); + testListResources(NUMBER_OF_RESOURCES + 1, null); } - public void testListResources(final String TEST_NAME, int expectedNumber, Collection> options) throws Exception { + public void testListResources( + int expectedNumber, Collection> options) + throws Exception { // GIVEN (1) Task task = getTestTask(); @@ -741,7 +683,7 @@ public void testListResources(final String TEST_NAME, int expectedNumber, Collec } else { AssertJUnit.fail("unexpected"); } - display("Got resources: "+resources); + display("Got resources: " + resources); assertEquals("Wrong number of resources", expectedNumber, resources.size()); // GIVEN (2) @@ -749,12 +691,9 @@ public void testListResources(final String TEST_NAME, int expectedNumber, Collec task = getTestTask(); result = task.getResult(); - ResultHandler handler = new ResultHandler() { - @Override - public boolean handle(PrismObject object, OperationResult parentResult) { - resources.add(object); - return true; - } + ResultHandler handler = (object, parentResult) -> { + resources.add(object); + return true; }; // WHEN (2) @@ -770,15 +709,13 @@ public boolean handle(PrismObject object, OperationResult parentRe } else { AssertJUnit.fail("unexpected"); } - display("Got resources: "+resources); + display("Got resources: " + resources); assertEquals("Wrong number of resources", expectedNumber, resources.size()); } @Test public void test377GetResourceNoConfiguration() throws Exception { - final String TEST_NAME = "test377GetResourceNoConfiguration"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -790,11 +727,11 @@ public void test377GetResourceNoConfiguration() throws Exception { display("getObject resource", resource); result.computeStatus(); display("getObject result", result); - assertEquals("Expected partial errror in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); + assertEquals("Expected partial error in result", OperationResultStatus.PARTIAL_ERROR, result.getStatus()); OperationResultType fetchResult = resource.asObjectable().getFetchResult(); display("resource.fetchResult", fetchResult); - assertEquals("Expected partial errror in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); + assertEquals("Expected partial error in fetchResult", OperationResultStatusType.PARTIAL_ERROR, fetchResult.getStatus()); assertNotNull("Null resource", resource); } @@ -802,15 +739,13 @@ public void test377GetResourceNoConfiguration() throws Exception { /** * Assign two resources to a user. One of them is looney, the other is not. The result should be that * the account on the good resource is created. - * + *

* This one dies on the lack of schema. - * + *

* MID-1248 */ @Test - public void test400AssignTwoResouresNotFound() throws Exception { - final String TEST_NAME = "test400AssignTwoResoures"; - + public void test400AssignTwoResourcesNotFound() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -835,13 +770,11 @@ public void test400AssignTwoResouresNotFound() throws Exception { /** * Assign two resources to a user. One of them is looney, the other is not. The result should be that * the account on the good resource is created. - * + *

* This one dies on connector error. */ @Test - public void test401AssignTwoResouresBroken() throws Exception { - final String TEST_NAME = "test401AssignTwoResouresBroken"; - + public void test401AssignTwoResourcesBroken() throws Exception { // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -883,8 +816,6 @@ private ObjectDelta createAssignTwoResourcesDelta(String badResourceOi */ @Test public void test500AssignResourceBlack() throws Exception { - final String TEST_NAME = "test500AssignResourceBlack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -906,7 +837,7 @@ public void test500AssignResourceBlack() throws Exception { PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); - String accountOid = getSingleLinkOid(userAfter); + assertThat(getSingleLinkOid(userAfter)).isNotNull(); assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); @@ -920,8 +851,6 @@ public void test500AssignResourceBlack() throws Exception { */ @Test public void test502ModifyUserEmployeeNumberNone() throws Exception { - final String TEST_NAME = "test502ModifyUserEmployeeNumberNone"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -938,7 +867,7 @@ public void test502ModifyUserEmployeeNumberNone() throws Exception { PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); - String accountOid = getSingleLinkOid(userAfter); + assertThat(getSingleLinkOid(userAfter)).isNotNull(); assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); @@ -952,8 +881,6 @@ public void test502ModifyUserEmployeeNumberNone() throws Exception { */ @Test public void test509UnassignResourceBlack() throws Exception { - final String TEST_NAME = "test509UnassignResourceBlack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -984,8 +911,6 @@ public void test509UnassignResourceBlack() throws Exception { */ @Test public void test510AssignResourceBlackError() throws Exception { - final String TEST_NAME = "test510AssignResourceBlackError"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1030,8 +955,6 @@ public void test510AssignResourceBlackError() throws Exception { */ @Test public void test512ReconcileUser() throws Exception { - final String TEST_NAME = "test512ReconcileUser"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1049,7 +972,7 @@ public void test512ReconcileUser() throws Exception { PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); - String accountOid = getSingleLinkOid(userAfter); + assertThat(getSingleLinkOid(userAfter)).isNotNull(); assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); } @@ -1061,8 +984,6 @@ public void test512ReconcileUser() throws Exception { */ @Test public void test514ModifyUserEmployeeNumberRuntime() throws Exception { - final String TEST_NAME = "test514ModifyUserEmployeeNumberRuntime"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1087,7 +1008,7 @@ public void test514ModifyUserEmployeeNumberRuntime() throws Exception { PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); - String accountOid = getSingleLinkOid(userAfter); + assertThat(getSingleLinkOid(userAfter)).isNotNull(); assertDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); @@ -1101,8 +1022,6 @@ public void test514ModifyUserEmployeeNumberRuntime() throws Exception { */ @Test public void test518UnassignResourceBlack() throws Exception { - final String TEST_NAME = "test518UnassignResourceBlack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1128,7 +1047,7 @@ public void test518UnassignResourceBlack() throws Exception { display("User after", userAfter); assertAssignments(userAfter, 0); // Still linked. There was error, we assume that the account might not be deleted. - String accountOid = getSingleLinkOid(userAfter); + assertThat(getSingleLinkOid(userAfter)).isNotNull(); // But we know that it is gone ... assertNoDummyAccount(RESOURCE_DUMMY_BLACK_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); @@ -1142,8 +1061,6 @@ public void test518UnassignResourceBlack() throws Exception { */ @Test public void test519ReconcileUser() throws Exception { - final String TEST_NAME = "test519ReconcileUser"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1172,8 +1089,6 @@ public void test519ReconcileUser() throws Exception { */ @Test public void test520AssignResourceEbonyError() throws Exception { - final String TEST_NAME = "test520AssignResourceEbonyError"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1212,8 +1127,6 @@ public void test520AssignResourceEbonyError() throws Exception { */ @Test public void test524ModifyUserEmployeeNumberRuntime() throws Exception { - final String TEST_NAME = "test524ModifyUserEmployeeNumberRuntime"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1230,7 +1143,7 @@ public void test524ModifyUserEmployeeNumberRuntime() throws Exception { PrismObject userAfter = getUser(USER_GUYBRUSH_OID); display("User after", userAfter); assertAssignments(userAfter, 1); - String accountOid = getSingleLinkOid(userAfter); + assertThat(getSingleLinkOid(userAfter)).isNotNull(); assertDummyAccount(RESOURCE_DUMMY_EBONY_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, ACCOUNT_GUYBRUSH_DUMMY_FULLNAME, true); @@ -1244,17 +1157,15 @@ public void test524ModifyUserEmployeeNumberRuntime() throws Exception { */ @Test public void test528UnassignResourceEbony() throws Exception { - final String TEST_NAME = "test528UnassignResourceEbony"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); prepareTest5xx(); assertUserBefore(USER_GUYBRUSH_OID) - .displayWithProjections() - .assertAssignments(1) - .assertLinks(1); + .displayWithProjections() + .assertAssignments(1) + .assertLinks(1); // WHEN when(); @@ -1266,14 +1177,14 @@ public void test528UnassignResourceEbony() throws Exception { assertPartialError(result); String shadowOid = assertUserAfter(USER_GUYBRUSH_OID) - .displayWithProjections() - .assertAssignments(0) - .singleLink() + .displayWithProjections() + .assertAssignments(0) + .singleLink() .resolveTarget() - .display() - // TODO: not sure whether this should be dead or alive - .assertTombstone() - .getOid(); + .display() + // TODO: not sure whether this should be dead or alive + .assertTombstone() + .getOid(); assertNoDummyAccount(RESOURCE_DUMMY_EBONY_NAME, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); @@ -1284,8 +1195,8 @@ public void test528UnassignResourceEbony() throws Exception { forceDeleteShadow(shadowOid); assertUserAfter(USER_GUYBRUSH_OID) - .assertAssignments(0) - .assertLinks(0); + .assertAssignments(0) + .assertLinks(0); assertNoShadow(shadowOid); } @@ -1296,8 +1207,6 @@ public void test528UnassignResourceEbony() throws Exception { */ @Test public void test600GuybrushAssignAccountDummyViolet() throws Exception { - final String TEST_NAME = "test600GuybrushAssignAccountDummyViolet"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1310,7 +1219,7 @@ public void test600GuybrushAssignAccountDummyViolet() throws Exception { assertNotReached(); } catch (ExpressionEvaluationException e) { - display("Exptected exception", e); + display("Expected exception", e); } // THEN @@ -1325,7 +1234,6 @@ public void test600GuybrushAssignAccountDummyViolet() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_BROKEN_VIOLET_NAME, "guybrush.3"); } - private void prepareTest5xx() throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); purgeProvisioningScriptHistory(RESOURCE_DUMMY_BLACK_NAME); @@ -1334,12 +1242,10 @@ private void prepareTest5xx() throws ObjectNotFoundException, SchemaException, O private void assertDummyScripts(String dummyName, String operation, String errorArg) { displayProvisioningScripts(dummyName); - ProvisioningScriptSpec script = new ProvisioningScriptSpec("operation:"+operation); + ProvisioningScriptSpec script = new ProvisioningScriptSpec("operation:" + operation); script.addArgSingle(DummyResource.POWERFAIL_ARG_ERROR, errorArg); script.setLanguage(DummyResource.SCRIPT_LANGUAGE_POWERFAIL); IntegrationTestTools.assertScripts(getDummyResource(dummyName).getScriptHistory(), script); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestModelWebServiceNegative.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestModelWebServiceNegative.java index 2737cf9bdf1..a02d4fa8db0 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestModelWebServiceNegative.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestModelWebServiceNegative.java @@ -22,10 +22,8 @@ import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.xnode.ValueParser; import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ModelExecuteOptionsType; import com.evolveum.midpoint.xml.ns._public.common.fault_3.FaultMessage; @@ -47,26 +45,13 @@ public class TestModelWebServiceNegative extends AbstractInitializedModelIntegrationTest { public static final File TEST_DIR = new File("src/test/resources/crud"); - public static final File TEST_CONTRACT_DIR = new File("src/test/resources/contract"); - - public static final File RESOURCE_MAROON_FILE = new File(TEST_DIR, "resource-dummy-maroon.xml"); - public static final String RESOURCE_MAROON_OID = "10000000-0000-0000-0000-00000000e104"; - - private static final String USER_MORGAN_OID = "c0c010c0-d34d-b33f-f00d-171171117777"; - private static final String USER_BLACKBEARD_OID = "c0c010c0-d34d-b33f-f00d-161161116666"; - - private static String accountOid; /** * First tests are positive, to make sure that this method works. */ @Test public void test100ModifyAccountExplicitType() throws Exception { - final String TEST_NAME = "test100ModifyUserAddAccount"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelWebServiceNegative.class.getName() + "." + TEST_NAME); - ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "foo", DOMUtil.XSD_STRING); @@ -89,11 +74,7 @@ public void test100ModifyAccountExplicitType() throws Exception { */ @Test public void test110ModifyAccountImplicitType() throws Exception { - final String TEST_NAME = "test110ModifyAccountImplicitType"; - // GIVEN - Task task = taskManager.createTaskInstance(TestModelWebServiceNegative.class.getName() + "." + TEST_NAME); - ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "bar", null); @@ -112,26 +93,22 @@ public void test110ModifyAccountImplicitType() throws Exception { } @Test - public void test200ModifyAccountWrongExplicitType() throws Exception { - final String TEST_NAME = "test200ModifyAccountWrongExplicitType"; - - // GIVEN - Task task = taskManager.createTaskInstance(TestModelWebServiceNegative.class.getName() + "." + TEST_NAME); - + public void test200ModifyAccountWrongExplicitType() { + given(); ObjectDeltaType objectChange = createShadowReplaceChange(ACCOUNT_SHADOW_GUYBRUSH_OID, "attributes/"+DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, "42", DOMUtil.XSD_INT); ObjectDeltaListType deltaList = new ObjectDeltaListType(); deltaList.getDelta().add(objectChange); - // WHEN, THEN - //assertExecuteChangesFailure(deltaList, null, SchemaViolationFaultType.class, "The value of type", "cannot be applied to attribute"); + expect(); assertExecuteChangesFailure(deltaList, null, SchemaViolationFaultType.class, "Expected", "but got class"); } - private void assertExecuteChangesFailure(ObjectDeltaListType deltaList, ModelExecuteOptionsType options, - Class expectedFaultTypeClass, String... messagePatterns) throws Exception { + private void assertExecuteChangesFailure( + ObjectDeltaListType deltaList, ModelExecuteOptionsType options, + Class expectedFaultTypeClass, String... messagePatterns) { try { modelWeb.executeChanges(deltaList, options); @@ -166,7 +143,7 @@ private ObjectDeltaType createShadowReplaceChange(String oid, String path, final itemDeltaType.setPath(itemPath); ValueParser valueParser = new ValueParser() { @Override - public String parse(QName typeName, XNodeProcessorEvaluationMode mode) throws SchemaException { + public String parse(QName typeName, XNodeProcessorEvaluationMode mode) { return value; } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStruct.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStruct.java index c85598f81ba..54b135b85bf 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStruct.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStruct.java @@ -6,6 +6,7 @@ */ package com.evolveum.midpoint.model.intest.orgstruct; +import static org.assertj.core.api.Assertions.assertThat; import static org.testng.AssertJUnit.assertEquals; import java.io.File; @@ -14,21 +15,6 @@ import java.util.List; import java.util.Set; -import com.evolveum.icf.dummy.resource.DummyAccount; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment; -import com.evolveum.midpoint.model.impl.expr.ModelExpressionThreadLocalHolder; -import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; -import com.evolveum.midpoint.prism.PrismReferenceDefinition; -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -36,7 +22,18 @@ import org.testng.annotations.Listeners; import org.testng.annotations.Test; +import com.evolveum.icf.dummy.resource.DummyAccount; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.impl.expr.ExpressionEnvironment; +import com.evolveum.midpoint.model.impl.expr.ModelExpressionThreadLocalHolder; +import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReferenceDefinition; +import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.ReferenceDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.schema.constants.SchemaConstants; @@ -48,23 +45,13 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.MidPointAsserts; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PartialProcessingOptionsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PartialProcessingTypeType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestOrgStruct extends AbstractInitializedModelIntegrationTest { @@ -120,8 +107,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010AddOrgStruct() throws Exception { - final String TEST_NAME = "test010AddOrgStruct"; - // Dummy, just to be overridden in subclasses addOrgStruct(); } @@ -132,16 +117,12 @@ protected void addOrgStruct() throws Exception { @Test public void test051OrgStructSanity() throws Exception { - final String TEST_NAME = "test051OrgStructSanity"; - // WHEN assertMonkeyIslandOrgSanity(); } @Test public void test052RootOrgQuery() throws Exception { - final String TEST_NAME = "test052RootOrgQuery"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -160,8 +141,6 @@ public void test052RootOrgQuery() throws Exception { @Test public void test100JackAssignOrgtarget() throws Exception { - final String TEST_NAME = "test100JackAssignOrgtarget"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -188,8 +167,6 @@ public void test100JackAssignOrgtarget() throws Exception { */ @Test public void test101JackAssignScummBar() throws Exception { - final String TEST_NAME = "test101JackAssignScummBar"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -214,8 +191,6 @@ public void test101JackAssignScummBar() throws Exception { @Test public void test102JackUnassignScummBar() throws Exception { - final String TEST_NAME = "test102JackUnassignScummBar"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -239,12 +214,10 @@ public void test102JackUnassignScummBar() throws Exception { */ @Test public void test201JackAssignScummBarAndSaveElaine() throws Exception { - final String TEST_NAME = "test201JackAssignScummBarAndSaveElaine"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ORG_SCUMM_BAR_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); modifications.add(createAssignmentModification(ORG_SAVE_ELAINE_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -270,8 +243,6 @@ public void test201JackAssignScummBarAndSaveElaine() throws Exception { */ @Test public void test202JackAssignMinistryOfOffense() throws Exception { - final String TEST_NAME = "test202JackAssignMinistryOfOffense"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -291,8 +262,6 @@ public void test202JackAssignMinistryOfOffense() throws Exception { @Test public void test207JackUnAssignScummBar() throws Exception { - final String TEST_NAME = "test207JackUnAssignScummBar"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -312,8 +281,6 @@ public void test207JackUnAssignScummBar() throws Exception { @Test public void test208JackUnassignAll() throws Exception { - final String TEST_NAME = "test208JackUnassignAll"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -338,12 +305,10 @@ public void test208JackUnassignAll() throws Exception { // besides Offense org assignment, we create also Defender role assignment (which indirectly creates Defense org assignment) @Test public void test210JackAssignMinistryOfOffenseMember() throws Exception { - final String TEST_NAME = "test210JackAssignMinistryOfOffenseMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); modifications.add(createAssignmentModification(ROLE_DEFENDER_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); modifications.add(createAssignmentModification(RESOURCE_DUMMY_ORGTARGET_OID, ShadowKindType.ACCOUNT, null, true)); @@ -368,8 +333,6 @@ public void test210JackAssignMinistryOfOffenseMember() throws Exception { @Test public void test211JackAssignMinistryOfOffenseMinister() throws Exception { - final String TEST_NAME = "test211JackAssignMinistryOfOffenseMinister"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -395,8 +358,6 @@ public void test211JackAssignMinistryOfOffenseMinister() throws Exception { @Test public void test212JackUnassignMinistryOfOffenseMember() throws Exception { - final String TEST_NAME = "test212JackUnassignMinistryOfOffenseMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -419,8 +380,6 @@ public void test212JackUnassignMinistryOfOffenseMember() throws Exception { @Test public void test213JackUnassignMinistryOfOffenseManager() throws Exception { - final String TEST_NAME = "test213JackUnassignMinistryOfOffenseManager"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -441,8 +400,6 @@ public void test213JackUnassignMinistryOfOffenseManager() throws Exception { @Test public void test220JackAssignMinistryOfOffenseMemberAgain() throws Exception { - final String TEST_NAME = "test220JackAssignMinistryOfOffenseMemberAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -469,17 +426,14 @@ public void test220JackAssignMinistryOfOffenseMemberAgain() throws Exception { */ @Test public void test221JackAssignScummBarAndSaveElaine() throws Exception { - final String TEST_NAME = "test221JackAssignScummBarAndSaveElaine"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ORG_SCUMM_BAR_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); modifications.add(createAssignmentModification(ORG_SAVE_ELAINE_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModifyDelta(USER_JACK_OID, modifications, UserType.class); - Collection> deltas = MiscSchemaUtil.createCollection(userDelta); // WHEN executeChanges(userDelta, null, task, result); @@ -496,19 +450,16 @@ public void test221JackAssignScummBarAndSaveElaine() throws Exception { assertMonkeyIslandOrgSanity(); } - @Test public void test223JackChangeMinistryOfOffenseMemberToManager() throws Exception { - final String TEST_NAME = "test221JackChangeMinistryOfOffenseMemberToManager"; - Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject jack = getUser(USER_JACK_OID); + assertThat(getUser(USER_JACK_OID)).isNotNull(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); - // this is now forbidden + // this is now forbidden TODO 2020: do we want to keep it around? // Long id = findAssignmentIdForTarget(jack, ORG_MINISTRY_OF_OFFENSE_OID); // PrismReferenceDefinition referenceDefinition = getUserDefinition() // .findItemDefinition( @@ -553,15 +504,12 @@ public void test223JackChangeMinistryOfOffenseMemberToManager() throws Exception assertMonkeyIslandOrgSanity(); } - /** * Recompute jack. Make sure nothing is changed. * MID-3384 */ @Test public void test230JackRecompute() throws Exception { - final String TEST_NAME = "test230JackRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); @@ -585,8 +533,6 @@ public void test230JackRecompute() throws Exception { */ @Test public void test232JackDestroyRefsAndRecompute() throws Exception { - final String TEST_NAME = "test232JackDestroyRefsAndRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -618,8 +564,6 @@ public void test232JackDestroyRefsAndRecompute() throws Exception { */ @Test public void test234JackDestroyRefsAndLightRecompute() throws Exception { - final String TEST_NAME = "test234JackDestroyRefsAndLightRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -650,8 +594,6 @@ public void test234JackDestroyRefsAndLightRecompute() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 0); } - - private void assertRefs23x() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User after", userAfter); @@ -679,12 +621,10 @@ private Long findAssignmentIdForTarget(PrismObject user, String target @Test public void test300JackUnassignAllOrgs() throws Exception { - final String TEST_NAME = "test300JackUnassignAllOrgs"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, SchemaConstants.ORG_MANAGER, null, null, false))); modifications.add((createAssignmentModification(ORG_SCUMM_BAR_OID, OrgType.COMPLEX_TYPE, null, null, null, false))); modifications.add((createAssignmentModification(ORG_SAVE_ELAINE_OID, OrgType.COMPLEX_TYPE, null, null, null, false))); @@ -711,8 +651,6 @@ public void test300JackUnassignAllOrgs() throws Exception { */ @Test public void test301JackAssignMinistryOfOffense() throws Exception { - final String TEST_NAME = "test301JackAssignMinistryOfOffense"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -736,12 +674,10 @@ public void test301JackAssignMinistryOfOffense() throws Exception { */ @Test public void test305JackConflictZeroAndMinus() throws Exception { - final String TEST_NAME = "test305JackConflictZeroAndMinus"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_DEFENDER_OID, RoleType.COMPLEX_TYPE, null, null, null, false))); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModifyDelta(USER_JACK_OID, modifications, UserType.class); @@ -767,16 +703,14 @@ public void test305JackConflictZeroAndMinus() throws Exception { */ @Test public void test307JackConflictPlusAndMinus() throws Exception { - final String TEST_NAME = "test307JackConflictPlusAndMinus"; - - executeConflictPlusAndMinus(TEST_NAME); + executeConflictPlusAndMinus(); } - protected void executeConflictPlusAndMinus(String TEST_NAME) throws Exception { + protected void executeConflictPlusAndMinus() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_DEFENDER_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ORG_MINISTRY_OF_DEFENSE_OID, OrgType.COMPLEX_TYPE, null, null, null, false))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -805,13 +739,11 @@ protected void executeConflictPlusAndMinus(String TEST_NAME) throws Exception { // also tests that when removing indirectly assigned org, it disappears from parentOrgRef @Test public void test308JackUnassignRoleDefender() throws Exception { - final String TEST_NAME = "test308JackUnassignRoleDefender"; - Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_DEFENDER_OID, RoleType.COMPLEX_TYPE, null, null, null, false))); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModifyDelta(USER_JACK_OID, modifications, UserType.class); @@ -836,17 +768,15 @@ public void test308JackUnassignRoleDefender() throws Exception { /** * Retrying last kind of conflict: adding the role assignment (that should add org assignment), * while deleting explicit org assignment - even it is not there! - * + *

* So this time there is originally NO parentOrgRef to Ministry of Defense/null. - * + *

* This situation is a kind of abnormal, but deleting non-present value is considered to be legal. * So we should treat a situation like this well. */ @Test public void test309JackConflictPlusAndMinusAgain() throws Exception { - final String TEST_NAME = "test309JackConflictPlusAndMinusAgain"; - - executeConflictPlusAndMinus(TEST_NAME); + executeConflictPlusAndMinus(); } /** @@ -854,8 +784,6 @@ public void test309JackConflictPlusAndMinusAgain() throws Exception { */ @Test public void test310JackConflictParentOrgRefAndAssignmentsAddOrg() throws Exception { - final String TEST_NAME = "test310JackConflictParentOrgRefAndAssignmentsAddOrg"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -887,12 +815,13 @@ public void test310JackConflictParentOrgRefAndAssignmentsAddOrg() throws Excepti */ @Test public void test349DeleteJack() throws Exception { - final String TEST_NAME = "test349DeleteJack"; - - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } - protected void executeDeleteJack(String TEST_NAME) throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + protected void executeDeleteJack() + throws ObjectAlreadyExistsException, ObjectNotFoundException, SchemaException, + ExpressionEvaluationException, CommunicationException, ConfigurationException, + PolicyViolationException, SecurityViolationException { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -908,7 +837,7 @@ protected void executeDeleteJack(String TEST_NAME) throws ObjectAlreadyExistsExc TestUtil.assertSuccess(result); try { - PrismObject user = getUser(USER_JACK_OID); + getUser(USER_JACK_OID); AssertJUnit.fail("Jack survived!"); } catch (ObjectNotFoundException e) { // This is expected @@ -920,8 +849,6 @@ protected void executeDeleteJack(String TEST_NAME) throws ObjectAlreadyExistsExc */ @Test public void test350AddJackAsMinistryOfOffenseManager() throws Exception { - final String TEST_NAME = "test350AddJackAsMinistryOfOffenseManager"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -969,8 +896,6 @@ public void test350AddJackAsMinistryOfOffenseManager() throws Exception { @Test public void test360ElaineAssignGovernor() throws Exception { - final String TEST_NAME = "test360ElaineAssignGovernor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1005,8 +930,6 @@ public void test360ElaineAssignGovernor() throws Exception { @Test public void test362ElaineAssignGovernmentMember() throws Exception { - final String TEST_NAME = "test362ElaineAssignGovernmentMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1042,8 +965,6 @@ public void test362ElaineAssignGovernmentMember() throws Exception { @Test public void test365GuybrushAssignSwashbucklerMember() throws Exception { - final String TEST_NAME = "test365GuybrushAssignSwashbucklerMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1085,8 +1006,6 @@ public void test365GuybrushAssignSwashbucklerMember() throws Exception { @Test public void test368GuybrushAssignSwashbucklerManager() throws Exception { - final String TEST_NAME = "test368GuybrushAssignSwashbucklerManager"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1130,8 +1049,6 @@ public void test368GuybrushAssignSwashbucklerManager() throws Exception { @Test public void test370BarbossaAssignOffenseMember() throws Exception { - final String TEST_NAME = "test370BarbossaAssignOffenseMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1180,8 +1097,6 @@ public void test370BarbossaAssignOffenseMember() throws Exception { @Test public void test372HermanAssignSwashbucklerMember() throws Exception { - final String TEST_NAME = "test365GuybrushAssignSwashbucklerMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userHerman = getUser(USER_HERMAN_OID); @@ -1239,9 +1154,7 @@ public void test372HermanAssignSwashbucklerMember() throws Exception { @Test public void test399DeleteJack() throws Exception { - final String TEST_NAME = "test399DeleteJack"; - - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } /** @@ -1249,8 +1162,6 @@ public void test399DeleteJack() throws Exception { */ @Test public void test400AddJackWithOrgUnit() throws Exception { - final String TEST_NAME = "test400AddJackWithOrgUnit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1277,14 +1188,12 @@ public void test400AddJackWithOrgUnit() throws Exception { @Test public void test402JackChangeMinistryOfOffenseMemberToManagerByAddingRemovingAssignment() throws Exception { - final String TEST_NAME = "test402JackChangeMinistryOfOffenseMemberToManagerByAddingRemovingAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject jack = getUser(USER_JACK_OID); + assertThat(getUser(USER_JACK_OID)).isNotNull(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, null, null, null, false)); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, SchemaConstants.ORG_MANAGER, null, null, true)); @@ -1312,14 +1221,12 @@ public void test402JackChangeMinistryOfOffenseMemberToManagerByAddingRemovingAss @Test public void test404JackChangeMinistryOfOffenseManagerToMemberByAddingRemovingAssignment() throws Exception { - final String TEST_NAME = "test404JackChangeMinistryOfOffenseManagerToMemberByAddingRemovingAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject jack = getUser(USER_JACK_OID); + assertThat(getUser(USER_JACK_OID)).isNotNull(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, SchemaConstants.ORG_MANAGER, null, null, false)); modifications.add(createAssignmentModification(ORG_MINISTRY_OF_OFFENSE_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); @@ -1345,9 +1252,7 @@ public void test404JackChangeMinistryOfOffenseManagerToMemberByAddingRemovingAss @Test public void test409DeleteJack() throws Exception { - final String TEST_NAME = "test409DeleteJack"; - - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } /** @@ -1356,8 +1261,6 @@ public void test409DeleteJack() throws Exception { */ @Test public void test410AddJackWithOrgUnit() throws Exception { - final String TEST_NAME = "test400AddJackWithOrgUnit"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1385,15 +1288,13 @@ public void test410AddJackWithOrgUnit() throws Exception { // this test should generate a SchemaException (modifying targetRef in assignment should be prohibited) @Test public void test412JackChangeMinistryOfOffenseMemberToManagerByModifyingAssignment() throws Exception { - final String TEST_NAME = "test412JackChangeMinistryOfOffenseMemberToManagerByModifyingAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject jack = getUser(USER_JACK_OID); Long id = findAssignmentIdForTarget(jack, ORG_MINISTRY_OF_OFFENSE_OID); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); PrismReferenceDefinition referenceDefinition = getUserDefinition() .findItemDefinition( @@ -1426,8 +1327,6 @@ public void test412JackChangeMinistryOfOffenseMemberToManagerByModifyingAssignme // import temp org + assign to jack (preparation for the next test) @Test public void test420JackAssignTempOrg() throws Exception { - final String TEST_NAME = "test420JackAssignTempOrg"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1449,8 +1348,6 @@ public void test420JackAssignTempOrg() throws Exception { // delete the org and then unassign it @Test public void test425JackUnassignDeletedOrg() throws Exception { - final String TEST_NAME = "test425JackUnassignDeletedOrg"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1477,8 +1374,6 @@ public void test425JackUnassignDeletedOrg() throws Exception { @Test public void test430JackAssignMetaroleOffender() throws Exception { - final String TEST_NAME = "test430JackAssignMetaroleOffender"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1487,7 +1382,7 @@ public void test430JackAssignMetaroleOffender() throws Exception { assertAssignedOrgs(userJackBefore, ORG_MINISTRY_OF_OFFENSE_OID); assertHasOrgs(userJackBefore, ORG_MINISTRY_OF_OFFENSE_OID); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ROLE_OFFENDER_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModifyDelta(USER_JACK_OID, modifications, UserType.class); @@ -1496,7 +1391,6 @@ public void test430JackAssignMetaroleOffender() throws Exception { // WHEN modelService.executeChanges(deltas, null, task, result); - // THEN result.computeStatus(); TestUtil.assertSuccess(result); @@ -1512,12 +1406,10 @@ public void test430JackAssignMetaroleOffender() throws Exception { @Test public void test431JackAssignMetaroleOffenderAdmin() throws Exception { - final String TEST_NAME = "test431JackAssignMetaroleOffenderAdmin"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(ROLE_OFFENDER_ADMIN_OID, RoleType.COMPLEX_TYPE, null, null, null, true)); ObjectDelta userDelta = prismContext.deltaFactory().object() .createModifyDelta(USER_JACK_OID, modifications, UserType.class); @@ -1526,7 +1418,6 @@ public void test431JackAssignMetaroleOffenderAdmin() throws Exception { // WHEN modelService.executeChanges(deltas, null, task, result); - // THEN PrismObject userJack = getUser(USER_JACK_OID); display("User jack after", userJack); @@ -1540,8 +1431,6 @@ public void test431JackAssignMetaroleOffenderAdmin() throws Exception { @Test public void test437JackUnassignOffender() throws Exception { - final String TEST_NAME = "test437JackUnassignOffender"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1567,8 +1456,6 @@ public void test437JackUnassignOffender() throws Exception { @Test public void test438JackUnassignOffenderAdmin() throws Exception { - final String TEST_NAME = "test438JackUnassignOffenderAdmin"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1593,8 +1480,6 @@ public void test438JackUnassignOffenderAdmin() throws Exception { @Test public void test439JackCleanup() throws Exception { - final String TEST_NAME = "test439JackCleanup"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1613,7 +1498,6 @@ public void test439JackCleanup() throws Exception { assertMonkeyIslandOrgSanity(); } - // Now let's test working with assignments when there is an object template that prescribes an org assignment // based on organizationalUnit property. @@ -1622,8 +1506,6 @@ public void test439JackCleanup() throws Exception { */ @Test public void test440JackModifyEmployeeTypeRolePirate() throws Exception { - final String TEST_NAME = "test440JackModifyEmployeeTypeRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1651,8 +1533,6 @@ public void test440JackModifyEmployeeTypeRolePirate() throws Exception { */ @Test public void test441JackModifyEmployeeTypeRoleCaptain() throws Exception { - final String TEST_NAME = "test441JackModifyEmployeeTypeRoleCaptain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1677,8 +1557,6 @@ public void test441JackModifyEmployeeTypeRoleCaptain() throws Exception { */ @Test public void test443JackModifyEmployeeTypeRoleNotExist() throws Exception { - final String TEST_NAME = "test443JackModifyEmployeeTypeRoleNotExist"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1698,14 +1576,11 @@ public void test443JackModifyEmployeeTypeRoleNotExist() throws Exception { assertMonkeyIslandOrgSanity(); } - /** * MID-3545 */ @Test public void test449JackModifyEmployeeTypeNull() throws Exception { - final String TEST_NAME = "test449JackModifyEmployeeTypeNull"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1726,8 +1601,6 @@ public void test449JackModifyEmployeeTypeNull() throws Exception { @Test public void test500JackEndPirate() throws Exception { - final String TEST_NAME = "test500JackEndPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1761,8 +1634,6 @@ public void test500JackEndPirate() throws Exception { */ @Test public void test510JackEndPirate() throws Exception { - final String TEST_NAME = "test510JackEndPirate"; - login(USER_JACK_USERNAME); Task task = getTestTask(); @@ -1789,23 +1660,18 @@ public void test510JackEndPirate() throws Exception { assertMonkeyIslandOrgSanity(); } - - @Test public void test799DeleteJack() throws Exception { - final String TEST_NAME = "test799DeleteJack"; - login(USER_ADMINISTRATOR_USERNAME); - executeDeleteJack(TEST_NAME); + executeDeleteJack(); } - // BEWARE, tests 800+ are executed in TestOrgStructMeta, so this class has to end with test799 and no jack present // --------------------------------------------------------------------------------------------------------------- protected void assertUserOrg(PrismObject user, String... orgOids) throws Exception { - for (String orgOid: orgOids) { + for (String orgOid : orgOids) { assertAssignedOrg(user, orgOid); assertHasOrg(user, orgOid); } @@ -1828,19 +1694,20 @@ private void assertManager(String userOid, String managerOid, String orgType, bo if (managers == null || managers.isEmpty()) { return; } else { - AssertJUnit.fail("Expected no manager for "+user+", but got "+managers); + AssertJUnit.fail("Expected no manager for " + user + ", but got " + managers); } } else { if (managers == null) { - AssertJUnit.fail("Expected manager for "+user+", but got no manager"); - } if (managers.size() != 1) { - AssertJUnit.fail("Expected one manager for "+user+", but got: "+managers); + AssertJUnit.fail("Expected manager for " + user + ", but got no manager"); + } + if (managers.size() != 1) { + AssertJUnit.fail("Expected one manager for " + user + ", but got: " + managers); } else { UserType manager = managers.iterator().next(); if (manager.getOid().equals(managerOid)) { return; } else { - AssertJUnit.fail("Expected manager with OID "+managerOid+" for "+user+", but got "+manager); + AssertJUnit.fail("Expected manager with OID " + managerOid + " for " + user + ", but got " + manager); } } } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructMeta.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructMeta.java index 2ebf0861ee3..f26cc1074e9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructMeta.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructMeta.java @@ -43,7 +43,6 @@ * Orgstruct test with a meta-role and focus mappings. * * @author Radovan Semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -139,9 +138,7 @@ protected void assertUserNoOrg(PrismObject user) throws Exception { @Test public void test800JackAssignScummBar() throws Exception { - final String TEST_NAME = "test800JackAssignScummBar"; - - Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); addObject(USER_JACK_FILE); @@ -166,9 +163,7 @@ public void test800JackAssignScummBar() throws Exception { @Test public void test802JackAssignOrganized() throws Exception { - final String TEST_NAME = "test802JackAssignOrganized"; - - Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -194,9 +189,7 @@ public void test802JackAssignOrganized() throws Exception { @Test public void test804JackUnAssignOrganized() throws Exception { - final String TEST_NAME = "test804JackUnAssignOrganized"; - - Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -221,9 +214,7 @@ public void test804JackUnAssignOrganized() throws Exception { @Test public void test809JackUnassignScummBar() throws Exception { - final String TEST_NAME = "test809JackUnassignScummBar"; - - Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -247,9 +238,7 @@ public void test809JackUnassignScummBar() throws Exception { */ @Test public void test810JackAssignScummBarOrganized() throws Exception { - final String TEST_NAME = "test810JackAssignScummBarOrganized"; - - Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Precondition @@ -282,9 +271,7 @@ public void test810JackAssignScummBarOrganized() throws Exception { @Test public void test890AddFictionalOrg() throws Exception { - final String TEST_NAME = "test890AddFictionalOrg"; - - Task task = taskManager.createTaskInstance(TestOrgStruct.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index f59698c360b..e7df8dbb191 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -146,12 +146,6 @@ public abstract class AbstractModelIntegrationTest extends AbstractIntegrationTe protected static final String CONNECTOR_DUMMY_VERSION = "2.0"; protected static final String CONNECTOR_DUMMY_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.icf.dummy/com.evolveum.icf.dummy.connector.DummyConnector"; - protected static final String CONNECTOR_LDAP_TYPE = "com.evolveum.polygon.connector.ldap.LdapConnector"; - protected static final String CONNECTOR_LDAP_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-ldap/com.evolveum.polygon.connector.ldap.LdapConnector"; - - protected static final String CONNECTOR_AD_TYPE = "Org.IdentityConnectors.ActiveDirectory.ActiveDirectoryConnector"; - protected static final String CONNECTOR_AD_NAMESPACE = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/ActiveDirectory.Connector/Org.IdentityConnectors.ActiveDirectory.ActiveDirectoryConnector"; - protected static final ItemPath ACTIVATION_ADMINISTRATIVE_STATUS_PATH = SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; protected static final ItemPath ACTIVATION_VALID_FROM_PATH = SchemaConstants.PATH_ACTIVATION_VALID_FROM; protected static final ItemPath ACTIVATION_VALID_TO_PATH = SchemaConstants.PATH_ACTIVATION_VALID_TO; @@ -475,7 +469,6 @@ protected void searchObjectsIterative(Class type, Task task = createPlainTask("searchObjectsIterative"); OperationResult result = task.getResult(); final MutableInt count = new MutableInt(0); - // Cannot convert to lambda here. Java does not want to understand the generic types properly. SearchResultMetadata searchMetadata = modelService.searchObjectsIterative(type, query, (object, oresult) -> { count.increment(); if (handler != null) { @@ -493,7 +486,8 @@ protected void assertUserProperty(String userOid, QName propertyName, Object... assertUserProperty(user, propertyName, expectedPropValues); } - protected void assertUserNoProperty(String userOid, QName propertyName) throws ObjectNotFoundException, SchemaException { + protected void assertUserNoProperty(String userOid, QName propertyName) + throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult("getObject"); PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); assertUserNoProperty(user, propertyName); @@ -584,7 +578,8 @@ protected void modifyObjectAddProperty(Class type, Str modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectReplaceContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) + protected void modifyObjectReplaceContainer( + Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -593,7 +588,8 @@ protected void modifyObjectRepla modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectAddContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) + protected void modifyObjectAddContainer( + Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -602,7 +598,8 @@ protected void modifyObjectAddCo modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectDeleteContainer(Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) + protected void modifyObjectDeleteContainer( + Class type, String oid, ItemPath propertyPath, Task task, OperationResult result, C... newRealValue) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -611,7 +608,8 @@ protected void modifyObjectDelet modelService.executeChanges(deltas, null, task, result); } - protected void modifyObjectReplaceReference(Class type, String oid, ItemPath refPath, Task task, OperationResult result, PrismReferenceValue... refVals) + protected void modifyObjectReplaceReference( + Class type, String oid, ItemPath refPath, Task task, OperationResult result, PrismReferenceValue... refVals) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { ObjectDelta objectDelta = prismContext.deltaFactory().object() @@ -647,7 +645,8 @@ protected void modifyAccountShadowReplace(String accountOid, ItemPath propertyPa modelService.executeChanges(deltas, null, task, result); } - protected ObjectDelta createOldNewPasswordDelta(String oid, String oldPassword, String newPassword) throws SchemaException { + protected ObjectDelta createOldNewPasswordDelta( + String oid, String oldPassword, String newPassword) throws SchemaException { ProtectedStringType oldPasswordPs = new ProtectedStringType(); oldPasswordPs.setClearValue(oldPassword); @@ -794,8 +793,10 @@ protected void assignRole(Class focusClass, Stri modifyAssignmentHolderAssignment(focusClass, focusOid, roleOid, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, result); } - protected void assignService(Class focusClass, String focusOid, String targetOid, ActivationType activationType, Task task, OperationResult result) throws ObjectNotFoundException, - SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + protected void assignService(Class focusClass, String focusOid, + String targetOid, ActivationType activationType, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyAssignmentHolderAssignment(focusClass, focusOid, targetOid, ServiceType.COMPLEX_TYPE, null, task, null, activationType, true, result); } @@ -806,8 +807,11 @@ protected void assignRole(Class focusClass, String focusOid modifyAssignmentHolderAssignment(focusClass, focusOid, roleOid, RoleType.COMPLEX_TYPE, null, task, null, activationType, true, options, result); } - protected void assignFocus(Class focusClass, String focusOid, QName targetType, String targetOid, QName relation, ActivationType activationType, Task task, OperationResult result) throws ObjectNotFoundException, - SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + protected void assignFocus(Class focusClass, + String focusOid, QName targetType, String targetOid, QName relation, + ActivationType activationType, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { modifyAssignmentHolderAssignment(focusClass, focusOid, targetOid, targetType, relation, task, null, activationType, true, result); } @@ -1044,7 +1048,7 @@ protected void assignOrg(Class focusType, String focusO throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { - modifyFocusAssignment(focusType, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, (Consumer) null, true, result); + modifyFocusAssignment(focusType, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, null, true, result); } protected void unassignOrg(String userOid, String orgOid) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { @@ -1080,7 +1084,7 @@ protected void unassignOrg(Class type, String focusOid, throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { - modifyFocusAssignment(type, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, (Consumer) null, false, result); + modifyFocusAssignment(type, focusOid, orgOid, OrgType.COMPLEX_TYPE, relation, task, null, false, result); } protected void modifyUserAssignment(String userOid, String roleOid, QName refType, QName relation, Task task, @@ -1230,7 +1234,7 @@ protected void unassignAll(PrismObject focusBefore, Tas /** * Creates unassign delta by removing each assignment individually by id. */ - protected ObjectDelta createUnassignAllDelta(PrismObject focusBefore) throws SchemaException { + protected ObjectDelta createUnassignAllDelta(PrismObject focusBefore) { Collection> modifications = new ArrayList<>(); for (AssignmentType assignmentType : focusBefore.asObjectable().getAssignment()) { modifications.add((createAssignmentModification(assignmentType.getId(), false))); @@ -1378,7 +1382,8 @@ protected ObjectDelta createAssignmentFocusD return prismContext.deltaFactory().object().createModifyDelta(focusOid, modifications, focusClass); } - protected ObjectDelta createAssignmentFocusEmptyDeleteDelta(PrismObject existingFocus, String roleOid, QName relation) throws SchemaException { + protected ObjectDelta createAssignmentFocusEmptyDeleteDelta( + PrismObject existingFocus, String roleOid, QName relation) { Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentEmptyDeleteModification(existingFocus, roleOid, relation))); return prismContext.deltaFactory().object().createModifyDelta( @@ -6179,12 +6184,9 @@ protected SearchResultList> assertSearch(C try { logAttempt("searchIterative", type, query); final List> iterativeObjects = new ArrayList<>(); - ResultHandler handler = new ResultHandler() { - @Override - public boolean handle(PrismObject object, OperationResult parentResult) { - iterativeObjects.add(object); - return true; - } + ResultHandler handler = (object, parentResult) -> { + iterativeObjects.add(object); + return true; }; modelService.searchObjectsIterative(type, query, handler, options, task, result); display("Search iterative returned", iterativeObjects.toString()); From f5ddd8a17778963f0e81141a0f91551e507891b4 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 17:55:02 +0100 Subject: [PATCH 18/55] ConnIdUtil.java: cleanup, removed unused parameter, dead code --- .../ucf/impl/connid/ConnIdUtil.java | 20 +++++-------------- 1 file changed, 5 insertions(+), 15 deletions(-) diff --git a/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java b/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java index 4ebe790b170..1ec5cf903c9 100644 --- a/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java +++ b/provisioning/ucf-impl-connid/src/main/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/ConnIdUtil.java @@ -10,7 +10,6 @@ import java.io.FileNotFoundException; import java.lang.reflect.InvocationTargetException; import java.net.ConnectException; -import java.net.UnknownHostException; import java.sql.SQLException; import java.sql.SQLSyntaxErrorException; import java.util.ArrayList; @@ -33,7 +32,6 @@ import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.util.logging.LoggingUtils; -import org.identityconnectors.common.security.GuardedByteArray; import org.identityconnectors.common.security.GuardedString; import org.identityconnectors.framework.common.exceptions.*; import org.identityconnectors.framework.common.objects.Attribute; @@ -49,7 +47,6 @@ import com.evolveum.midpoint.prism.crypto.Protector; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; -import com.evolveum.midpoint.prism.xml.XsdTypeMapper; import com.evolveum.midpoint.provisioning.ucf.api.GenericFrameworkException; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; @@ -59,7 +56,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.PrettyPrinter; -import com.evolveum.midpoint.util.exception.CommonException; import com.evolveum.midpoint.util.exception.CommunicationException; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; @@ -68,7 +64,6 @@ import com.evolveum.midpoint.util.exception.SecurityViolationException; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.prism.xml.ns._public.types_3.ProtectedByteArrayType; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; import org.identityconnectors.framework.impl.api.remote.RemoteWrappedException; @@ -228,7 +223,7 @@ static Throwable processConnIdException(Throwable connIdException, String desc, } // Introspect the inner exceptions and look for known causes - knownCause = lookForKnownCause(connIdException, connIdException, connIdResult); + knownCause = lookForKnownCause(connIdException, connIdResult); if (knownCause != null) { // LOGGER.error("LOOK FOR KNOWN EXCEPTION: {} -> {}", connIdException.getClass().getName(), knownCause.getClass().getName()); connIdResult.recordFatalError(knownCause); @@ -313,7 +308,7 @@ private static Exception processConnectorException(ConnectorException connIdExce } else if (connIdException instanceof RetryableException) { Exception newEx = new CommunicationException(createMessageFromAllExceptions(null, connIdException)); - connIdResult.recordFatalError("Retryable errror: " + connIdException.getMessage(), newEx); + connIdResult.recordFatalError("Retryable error: " + connIdException.getMessage(), newEx); return newEx; } else if (connIdException instanceof ConnectorSecurityException) { @@ -335,9 +330,7 @@ private static Exception processConnectorException(ConnectorException connIdExce return null; } - private static Exception lookForKnownCause(Throwable ex, - Throwable originalException, OperationResult parentResult) { - + private static Exception lookForKnownCause(Throwable ex, OperationResult parentResult) { if (ex.getClass().getPackage().equals(SchemaException.class.getPackage())) { // Common midPoint exceptions, pass through // Those may get here from the inner calls of handle() methods from the connector. @@ -378,7 +371,7 @@ private static Exception lookForKnownCause(Throwable ex, // This is thrown by LDAP connector and may be also throw by similar // connectors javax.naming.directory.InvalidAttributeValueException e = (javax.naming.directory.InvalidAttributeValueException) ex; - Exception newEx = null; + Exception newEx; if (e.getExplanation().contains("unique attribute conflict")){ newEx = new ObjectAlreadyExistsException(createMessageFromAllExceptions("Invalid attribute", ex)); } else{ @@ -431,7 +424,7 @@ private static Exception lookForKnownCause(Throwable ex, return null; } else { // Otherwise go one level deeper ... - return lookForKnownCause(ex.getCause(), originalException, + return lookForKnownCause(ex.getCause(), parentResult); } } @@ -666,14 +659,11 @@ public static GuardedString toGuardedString(ProtectedStringType ps, Protector pr if (ps.getClearValue() == null) { return null; } -// LOGGER.warn("Using cleartext value for {}", propertyName); return new GuardedString(ps.getClearValue().toCharArray()); } try { return new GuardedString(protector.decryptString(ps).toCharArray()); } catch (EncryptionException e) { -// LOGGER.error("Unable to decrypt value of element {}: {}", -// new Object[] { propertyName, e.getMessage(), e }); throw new SystemException("Unable to decrypt value of element " + propertyName + ": " + e.getMessage(), e); } From 6bb06e73eb2f63529702a6ee27289fd238b27148 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 17:56:07 +0100 Subject: [PATCH 19/55] ProvisioningServiceImpl: code cleanup, removed long unused private stuff --- .../impl/ProvisioningServiceImpl.java | 36 +++++-------------- 1 file changed, 8 insertions(+), 28 deletions(-) diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java index 8f960e70d5d..c05a354644c 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/impl/ProvisioningServiceImpl.java @@ -39,7 +39,6 @@ import com.evolveum.midpoint.prism.Objectable; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.crypto.EncryptionException; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.delta.ObjectDelta; @@ -107,8 +106,6 @@ public class ProvisioningServiceImpl implements ProvisioningService, SystemConfi @Qualifier("cacheRepositoryService") private RepositoryService cacheRepositoryService; - private PrismObjectDefinition resourceObjectShadowDefinition; - private SystemConfigurationType systemConfiguration; private static final Trace LOGGER = TraceManager.getTrace(ProvisioningServiceImpl.class); @@ -269,7 +266,7 @@ public String addObject(PrismObject object, OperationP result.addArbitraryObjectAsParam("scripts", scripts); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, ProvisioningServiceImpl.class); - String oid = null; + String oid; if (object.canRepresent(ShadowType.class)) { try { // calling shadow cache to add object @@ -491,7 +488,7 @@ private SearchResultList> searchRepoObject // TODO: what else do to with objResult?? - } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | ExpressionEvaluationException e) { + } catch (ObjectNotFoundException | SchemaException | ExpressionEvaluationException e) { LOGGER.error("Error while completing {}: {}-{}. Using non-complete object.", repoObject, e.getMessage(), e); objResult.recordFatalError(e); repoObject.asObjectable().setFetchResult(objResult.createOperationResultType()); @@ -518,8 +515,8 @@ private SearchResultList> searchRepoObject // TODO: move to ResourceManager and ConnectorManager // the shadow-related code is already in the ShadowCache - private PrismObject completeObject(Class type, PrismObject inObject, - Collection> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + private PrismObject completeObject( + Class type, PrismObject inObject, Collection> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, ExpressionEvaluationException { if (ResourceType.class.equals(type)) { //noinspection unchecked @@ -530,7 +527,6 @@ private PrismObject completeObject(Class type, Pris throw new IllegalStateException("BOOOM!"); } else { //TODO: connectors etc.. - } return inObject; } @@ -551,7 +547,7 @@ public Integer countObjects(Class type, ObjectQuery qu LOGGER.trace("Start of counting objects. Query:\n{}", query != null ? query.debugDump(1) : " (null)"); } - if (filter != null && filter instanceof NoneFilter) { + if (filter instanceof NoneFilter) { result.recordSuccessIfUnknown(); result.cleanupResult(); LOGGER.trace("Finished counting. Nothing to do. Filter is NONE"); @@ -570,11 +566,9 @@ public Integer countObjects(Class type, ObjectQuery qu Integer count; try { - count = shadowCache.countObjects(query, task, result); result.computeStatus(); - } catch (ConfigurationException | CommunicationException | ObjectNotFoundException | SchemaException | ExpressionEvaluationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, null, e); throw e; @@ -704,7 +698,7 @@ public PrismObject deleteObject(Class type, String ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: security violation: " + e.getMessage(), e); throw e; } catch (ExpressionEvaluationException e) { - ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: expression errror: " + e.getMessage(), e); + ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: expression error: " + e.getMessage(), e); throw e; } catch (PolicyViolationException | RuntimeException | Error e) { ProvisioningUtil.recordFatalError(LOGGER, result, "Couldn't delete object: " + e.getMessage(), e); @@ -743,9 +737,8 @@ public PrismObject deleteObject(Class type, String * @see com.evolveum.midpoint.provisioning.api.ProvisioningService#executeScript(java.lang.Class, java.lang.String, com.evolveum.midpoint.xml.ns._public.common.common_3.ProvisioningScriptType, com.evolveum.midpoint.task.api.Task, com.evolveum.midpoint.schema.result.OperationResult) */ @Override - public Object executeScript(String resourceOid, ProvisioningScriptType script, - Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException, - CommunicationException, ConfigurationException, ExpressionEvaluationException { + public Object executeScript(String resourceOid, ProvisioningScriptType script, Task task, OperationResult parentResult) + throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Validate.notNull(resourceOid, "Oid of object for script execution must not be null."); Validate.notNull(parentResult, "Operation result must not be null."); @@ -1118,11 +1111,6 @@ public void applyDefinition(PrismObject object, Task t } } - private void setProtectedShadow(PrismObject shdaow, OperationResult result) - throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - shadowCache.setProtectedShadow(shdaow, result); - } - @Override public void applyDefinition(Class type, ObjectQuery query, Task task, OperationResult parentResult) throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -1252,14 +1240,6 @@ public void exitConstraintsCheckerCache() { ConstraintsChecker.exitCache(); } - private PrismObjectDefinition getResourceObjectShadowDefinition() { - if (resourceObjectShadowDefinition == null) { - resourceObjectShadowDefinition = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass( - ShadowType.class); - } - return resourceObjectShadowDefinition; - } - private PrismObject getRepoObject(Class type, String oid, Collection> options, OperationResult result) throws ObjectNotFoundException, SchemaException { From 457c71014546dc6c80b11450db13b4aba51b42c6 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Fri, 6 Mar 2020 21:37:26 +0100 Subject: [PATCH 20/55] no more TEST_NAME in model-intest classes --- .../intest/negative/TestAssignmentErrors.java | 11 +- .../orgstruct/TestOrgStructCaribbean.java | 68 ++--- .../intest/persona/AbstractPersonaTest.java | 23 +- .../intest/persona/TestPersonaPassword.java | 10 +- .../intest/rbac/TestAssignmentValidity.java | 154 ++--------- .../model/intest/rbac/TestAutoassign.java | 11 - .../model/intest/rbac/TestMetaMeta.java | 122 +++------ .../midpoint/model/intest/rbac/TestRbac.java | 210 +-------------- .../intest/rbac/TestSegregationOfDuties.java | 225 +++------------- .../intest/security/TestSecurityAdvanced.java | 61 +---- .../intest/security/TestSecurityBasic.java | 24 +- .../intest/security/TestSecurityMedium.java | 7 - .../security/TestSecurityMultitenant.java | 17 +- .../security/TestSecurityPrincipal.java | 16 -- .../model/intest/sync/TestImportRecon.java | 155 +++++------ .../intest/sync/TestParallelDiscovery.java | 6 - .../sync/TestParallelSynchronization.java | 6 - .../sync/TestValidityRecomputeTask.java | 250 +++++------------- 18 files changed, 296 insertions(+), 1080 deletions(-) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java index 732c48e3cee..85c291714eb 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/negative/TestAssignmentErrors.java @@ -522,12 +522,10 @@ public void test220UserAssignAccountDeletedShadowRecomputeSync() throws Exceptio //see git commit: 7052f9628a76815d27a119090a97ec57fbdebaec @Test public void test222UserAssignAccountDeletedShadowRecomputeNoSync() throws Exception { - final String TEST_NAME = "test222UserAssignAccountDeletedShadowRecomputeNoSync"; - // GIVEN - PrismObject user = setupUserAssignAccountDeletedShadowRecompute(RESOURCE_DUMMY_RED_OID, - RESOURCE_DUMMY_RED_NAME, USER_BFET_NAME, USER_BFET_FULLNAME); - Task task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); + PrismObject user = setupUserAssignAccountDeletedShadowRecompute( + RESOURCE_DUMMY_RED_OID, RESOURCE_DUMMY_RED_NAME, USER_BFET_NAME, USER_BFET_FULLNAME); + Task task = createPlainTask(); OperationResult result = task.getResult(); try { @@ -547,7 +545,7 @@ public void test222UserAssignAccountDeletedShadowRecomputeNoSync() throws Except // and again ... - task = taskManager.createTaskInstance(TestAssignmentErrors.class.getName() + "." + TEST_NAME); + task = createPlainTask(); result = task.getResult(); try { @@ -564,7 +562,6 @@ public void test222UserAssignAccountDeletedShadowRecomputeNoSync() throws Except user = getUser(user.getOid()); display("User after", user); assertNoLinkedAccount(user); - } /** diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java index be3601033a4..a901a7e061b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/orgstruct/TestOrgStructCaribbean.java @@ -8,15 +8,14 @@ import java.io.File; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; - import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Listeners; import org.testng.annotations.Test; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; @@ -28,9 +27,8 @@ /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationTest { @@ -38,7 +36,6 @@ public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationT public static final File TEST_DIR = new File("src/test/resources/orgstruct"); protected static final File ORG_CARIBBEAN_FILE = new File(TEST_DIR, "org-caribbean.xml"); - protected static final String ORG_CARIBBEAN_TOP_OID = "00000000-8888-6666-0000-c00000000001"; protected static final String ORG_CARIBBEAN_THE_CROWN_OID = "00000000-8888-6666-0000-c00000000002"; protected static final String ORG_CARIBBEAN_JAMAICA_OID = "00000000-8888-6666-0000-c00000000003"; protected static final String ORG_CARIBBEAN_DEPARTMENT_OF_THINGS_OID = "00000000-8888-6666-0000-c00000000004"; @@ -54,7 +51,6 @@ public class TestOrgStructCaribbean extends AbstractInitializedModelIntegrationT public static final String USER_PINTEL_USERNAME = "pintel"; public static final File ROLE_META_PIRACY_ORG_FILE = new File(TEST_DIR, "role-meta-piracy-org.xml"); - public static final String ROLE_META_PIRACY_ORG_OID = "d534f1b2-a26c-11e6-abf5-e71dff038896"; @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -64,19 +60,14 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti addObject(USER_PINTEL_FILE); addObject(ROLE_META_PIRACY_ORG_FILE); - - //DebugUtil.setDetailedDebugDump(true); } - /** * MID-3448 */ @Test public void test100AddOrgCaribbean() throws Exception { - final String TEST_NAME = "test100AddOrgCaribbean"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -109,9 +100,7 @@ public void test100AddOrgCaribbean() throws Exception { */ @Test public void test102RecomputeJamaica() throws Exception { - final String TEST_NAME = "test102RecomputeJamaica"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -139,9 +128,7 @@ public void test102RecomputeJamaica() throws Exception { */ @Test public void test103ReconcileJamaica() throws Exception { - final String TEST_NAME = "test103ReconcileJamaica"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -169,9 +156,7 @@ public void test103ReconcileJamaica() throws Exception { */ @Test public void test104RecomputeGovernor() throws Exception { - final String TEST_NAME = "test104RecomputeGovernor"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -199,9 +184,7 @@ public void test104RecomputeGovernor() throws Exception { */ @Test public void test105ReconcileGovernor() throws Exception { - final String TEST_NAME = "test105ReconcileGovernor"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -227,14 +210,12 @@ public void test105ReconcileGovernor() throws Exception { /** * Jamaica has an inducement to Monkey Island Governor Office. * Sub-orgs of Jamaica should appear under Governor office. - * + *

* MID-3448 */ @Test public void test106RecomputeDoT() throws Exception { - final String TEST_NAME = "test106RecomputeDoT"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -268,9 +249,7 @@ public void test106RecomputeDoT() throws Exception { */ @Test public void test107ReconcileDoT() throws Exception { - final String TEST_NAME = "test107ReconcileDoT"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -302,14 +281,12 @@ public void test107ReconcileDoT() throws Exception { * Department of People (DoP) has in inducement to Monkey Island Scumm Bar. * But that inducement is limited to UserType. Therefore sub-orgs of * DoP should not not appear under Scumm Bar. - * + *

* Related to MID-3448 */ @Test public void test110RecomputeDoP() throws Exception { - final String TEST_NAME = "test110RecomputeDoP"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -336,14 +313,12 @@ public void test110RecomputeDoP() throws Exception { * That inducement is limited to UserType. Therefore sub-orgs of * DoP should not not appear under Scumm Bar. But when Jack is assigned * to the DoP he should also appear under Scumm Bar. - * + *

* Related to MID-3448 */ @Test public void test115AssignJackToDoP() throws Exception { - final String TEST_NAME = "test115AssignJackToDoP"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_JACK_USERNAME); @@ -391,9 +366,7 @@ public void test115AssignJackToDoP() throws Exception { */ @Test public void test120AssignBarbossaDoTManager() throws Exception { - final String TEST_NAME = "test120AssignBarbossaDoTManager"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_BARBOSSA_USERNAME); @@ -428,9 +401,7 @@ public void test120AssignBarbossaDoTManager() throws Exception { */ @Test public void test130AssignGibbsAsJacksDeputy() throws Exception { - final String TEST_NAME = "test130AssignGibbsAsJacksDeputy"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_GIBBS_USERNAME); @@ -459,7 +430,6 @@ public void test130AssignGibbsAsJacksDeputy() throws Exception { DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, "Pirate"); assertNoDummyAccount(RESOURCE_DUMMY_RED_NAME, USER_GIBBS_USERNAME); - } /** @@ -467,9 +437,7 @@ public void test130AssignGibbsAsJacksDeputy() throws Exception { */ @Test public void test140AssignPintelAsBarbossasDeputy() throws Exception { - final String TEST_NAME = "test140AssignPintelAsBarbossasDeputy"; - - Task task = taskManager.createTaskInstance(TestOrgStructCaribbean.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assertNoDummyAccount(RESOURCE_DUMMY_YELLOW_NAME, USER_PINTEL_USERNAME); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/AbstractPersonaTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/AbstractPersonaTest.java index 0d55ea714ea..a4ad66e46b9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/AbstractPersonaTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/AbstractPersonaTest.java @@ -24,7 +24,6 @@ /** * @author semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -57,8 +56,6 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test100AssignRolePersonaAdminToJack() throws Exception { - final String TEST_NAME = "test100AssignRolePersonaAdminToJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -93,8 +90,6 @@ public void test100AssignRolePersonaAdminToJack() throws Exception { @Test public void test102RecomputeUserJack() throws Exception { - final String TEST_NAME = "test102RecomputeUserJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -112,8 +107,6 @@ public void test102RecomputeUserJack() throws Exception { @Test public void test103ReconcileUserJack() throws Exception { - final String TEST_NAME = "test103ReconcileUserJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -131,8 +124,6 @@ public void test103ReconcileUserJack() throws Exception { @Test public void test104RecomputeJackAdminPersona() throws Exception { - final String TEST_NAME = "test104RecomputeJackAdminPersona"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -150,8 +141,6 @@ public void test104RecomputeJackAdminPersona() throws Exception { @Test public void test105ReconcileJackAdminPersona() throws Exception { - final String TEST_NAME = "test105ReconcileJackAdminPersona"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -186,8 +175,6 @@ private void assertUserJack11x() throws Exception { @Test public void test120ModifyJackGivenName() throws Exception { - final String TEST_NAME = "test120ModifyJackGivenName"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -223,8 +210,6 @@ public void test120ModifyJackGivenName() throws Exception { @Test public void test140ModifyUserJackPassword() throws Exception { - final String TEST_NAME = "test140ModifyUserJackPassword"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -257,8 +242,6 @@ public void test140ModifyUserJackPassword() throws Exception { @Test public void test142ModifyPersonaPassword() throws Exception { - final String TEST_NAME = "test142ModifyPersonaPassword"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -297,8 +280,6 @@ protected void assertPersonaAfterPersonaPasswordChange(PrismObject per @Test public void test145ModifyPersonaPasswordBack() throws Exception { - final String TEST_NAME = "test145ModifyPersonaPasswordBack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -331,14 +312,12 @@ public void test145ModifyPersonaPasswordBack() throws Exception { } - // TODO: assign some accouts/roles to user and persona, make sure they are independent + // TODO: assign some accounts/roles to user and persona, make sure they are independent // TODO: independent change in the persona @Test public void test199UnassignRolePersonaAdminFromJack() throws Exception { - final String TEST_NAME = "test199UnassignRolePersonaAdminFromJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/TestPersonaPassword.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/TestPersonaPassword.java index cdeb66a56fe..c97c0a6786f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/TestPersonaPassword.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/persona/TestPersonaPassword.java @@ -38,7 +38,6 @@ public class TestPersonaPassword extends AbstractPersonaTest { protected static final String SECURITY_POLICY_PERSONA_OID = "51545f14-b4df-11e7-a37a-d37b7c2b3f4c"; protected static final File PASSWORD_POLICY_PERSONA_FILE = new File(TEST_DIR, "password-policy-persona.xml"); - protected static final String PASSWORD_POLICY_PERSONA_OID = "5d9e068a-b4df-11e7-be31-a7b0fef77d95"; @Override public void initSystem(Task initTask, OperationResult initResult) @@ -57,20 +56,19 @@ protected File getPersonaObjectTemplateFile() { } @Override - protected void assertPersonaInitialPassword(PrismObject persona, String userPassword) throws Exception { + protected void assertPersonaInitialPassword(PrismObject persona, String userPassword) { assertUserNoPassword(persona); } @Override - protected void assertPersonaAfterUserPasswordChange(PrismObject persona, String oldPersonaPassword, String newUserPassword) throws Exception { + protected void assertPersonaAfterUserPasswordChange( + PrismObject persona, String oldPersonaPassword, String newUserPassword) { assertUserNoPassword(persona); } @Test @Override public void test145ModifyPersonaPasswordBack() throws Exception { - final String TEST_NAME = "test145ModifyPersonaPasswordBack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -96,8 +94,6 @@ public void test145ModifyPersonaPasswordBack() throws Exception { then(); assertFailure(result); - XMLGregorianCalendar endCal = clock.currentTimeXMLGregorianCalendar(); - PrismObject userAfter = getUser(USER_JACK_OID); display("User after change execution", userAfter); assertUser(userAfter, USER_JACK_OID, USER_JACK_USERNAME, USER_JACK_FULL_NAME, USER_JACK_GIVEN_NAME_NEW, USER_JACK_FAMILY_NAME); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAssignmentValidity.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAssignmentValidity.java index 72cbcf99b77..dcff58de1f3 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAssignmentValidity.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAssignmentValidity.java @@ -8,8 +8,6 @@ import javax.xml.datatype.XMLGregorianCalendar; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -17,20 +15,17 @@ import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestAssignmentValidity extends AbstractRbacTest { @@ -40,7 +35,6 @@ public class TestAssignmentValidity extends AbstractRbacTest { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); -// InternalsConfig.setTestingPaths(TestingPaths.REVERSED); } /** @@ -48,8 +42,6 @@ public void initSystem(Task initTask, OperationResult initResult) */ @Test public void test100JackAssignRolePirateValidTo() throws Exception { - final String TEST_NAME = "test100JackAssignRolePirateValidTo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -89,8 +81,6 @@ public void test100JackAssignRolePirateValidTo() throws Exception { */ @Test public void test102Forward15min() throws Exception { - final String TEST_NAME = "test102Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -120,8 +110,6 @@ public void test102Forward15min() throws Exception { */ @Test public void test104JackAssignRolePirateAgain() throws Exception { - final String TEST_NAME = "test104JackAssignRolePirateAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -155,8 +143,6 @@ public void test104JackAssignRolePirateAgain() throws Exception { */ @Test public void test106JackUnassignRolePirateValid() throws Exception { - final String TEST_NAME = "test106JackUnassignRolePirateValid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -183,7 +169,7 @@ public void test106JackUnassignRolePirateValid() throws Exception { */ @Test public void test109JackUnassignAll() throws Exception { - unassignAll("test109JackUnassignAll"); + unassignAll(); } /** @@ -193,8 +179,6 @@ public void test109JackUnassignAll() throws Exception { */ @Test public void test110JackAssignRolePirateValidToRaw() throws Exception { - final String TEST_NAME = "test110JackAssignRolePirateValidToRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -232,8 +216,6 @@ public void test110JackAssignRolePirateValidToRaw() throws Exception { */ @Test public void test111RecomputeJack() throws Exception { - final String TEST_NAME = "test111RecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -265,8 +247,6 @@ public void test111RecomputeJack() throws Exception { */ @Test public void test112Forward15min() throws Exception { - final String TEST_NAME = "test102Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -296,8 +276,6 @@ public void test112Forward15min() throws Exception { */ @Test public void test114JackAssignRolePirateAgain() throws Exception { - final String TEST_NAME = "test114JackAssignRolePirateAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -330,7 +308,7 @@ public void test114JackAssignRolePirateAgain() throws Exception { */ @Test public void test119JackUnassignAll() throws Exception { - unassignAll("test119JackUnassignAll"); + unassignAll(); } /** @@ -339,8 +317,6 @@ public void test119JackUnassignAll() throws Exception { */ @Test public void test120JackAssignRoleSailorValidTo() throws Exception { - final String TEST_NAME = "test120JackAssignRoleSailorValidTo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -380,8 +356,6 @@ public void test120JackAssignRoleSailorValidTo() throws Exception { */ @Test public void test122Forward15min() throws Exception { - final String TEST_NAME = "test122Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -411,8 +385,6 @@ public void test122Forward15min() throws Exception { */ @Test public void test124JackAssignRoleSailorAgain() throws Exception { - final String TEST_NAME = "test124JackAssignRoleSailorAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -445,7 +417,7 @@ public void test124JackAssignRoleSailorAgain() throws Exception { */ @Test public void test129JackUnassignAll() throws Exception { - unassignAll("test129JackUnassignAll"); + unassignAll(); } /** @@ -455,8 +427,6 @@ public void test129JackUnassignAll() throws Exception { */ @Test public void test130JackAssignRoleSailorValidToRaw() throws Exception { - final String TEST_NAME = "test130JackAssignRoleSailorValidToRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -494,8 +464,6 @@ public void test130JackAssignRoleSailorValidToRaw() throws Exception { */ @Test public void test131RecomputeJack() throws Exception { - final String TEST_NAME = "test131RecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -527,8 +495,6 @@ public void test131RecomputeJack() throws Exception { */ @Test public void test132Forward15min() throws Exception { - final String TEST_NAME = "test132Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -558,8 +524,6 @@ public void test132Forward15min() throws Exception { */ @Test public void test134JackAssignRoleSailorAgain() throws Exception { - final String TEST_NAME = "test134JackAssignRoleSailorAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -592,7 +556,7 @@ public void test134JackAssignRoleSailorAgain() throws Exception { */ @Test public void test139JackUnassignAll() throws Exception { - unassignAll("test139JackUnassignAll"); + unassignAll(); } /** @@ -602,8 +566,6 @@ public void test139JackUnassignAll() throws Exception { */ @Test public void test140JackAssignRoleSailorValidToRaw() throws Exception { - final String TEST_NAME = "test140JackAssignRoleSailorValidToRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -642,10 +604,6 @@ public void test140JackAssignRoleSailorValidToRaw() throws Exception { */ @Test public void test142Forward15min() throws Exception { - final String TEST_NAME = "test142Forward15min"; - - Task task = getTestTask(); - // WHEN when(); clockForward("PT15M"); @@ -670,8 +628,6 @@ public void test142Forward15min() throws Exception { */ @Test public void test144JackAssignRoleSailorAgain() throws Exception { - final String TEST_NAME = "test144JackAssignRoleSailorAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -704,7 +660,7 @@ public void test144JackAssignRoleSailorAgain() throws Exception { */ @Test public void test149JackUnassignAll() throws Exception { - unassignAll("test149JackUnassignAll"); + unassignAll(); } /** @@ -712,8 +668,6 @@ public void test149JackUnassignAll() throws Exception { */ @Test public void test150JackAssignRolePirate() throws Exception { - final String TEST_NAME = "test150JackAssignRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -747,8 +701,6 @@ public void test150JackAssignRolePirate() throws Exception { */ @Test public void test151JackAssignRoleSailorValidTo() throws Exception { - final String TEST_NAME = "test151JackAssignRoleSailorValidTo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -788,8 +740,6 @@ public void test151JackAssignRoleSailorValidTo() throws Exception { */ @Test public void test153Forward15min() throws Exception { - final String TEST_NAME = "test153Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -821,8 +771,6 @@ public void test153Forward15min() throws Exception { */ @Test public void test154JackAssignRoleSailorAgain() throws Exception { - final String TEST_NAME = "test154JackAssignRoleSailorAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -851,7 +799,7 @@ public void test154JackAssignRoleSailorAgain() throws Exception { */ @Test public void test159JackUnassignAll() throws Exception { - unassignAll("test159JackUnassignAll"); + unassignAll(); } /** @@ -859,8 +807,6 @@ public void test159JackUnassignAll() throws Exception { */ @Test public void test160JackAssignRolePirate() throws Exception { - final String TEST_NAME = "test160JackAssignRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -893,8 +839,6 @@ public void test160JackAssignRolePirate() throws Exception { */ @Test public void test161JackAssignRoleSailorValidToRaw() throws Exception { - final String TEST_NAME = "test161JackAssignRoleSailorValidToRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -928,7 +872,6 @@ public void test161JackAssignRoleSailorValidToRaw() throws Exception { assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); // SAILOR is not here, we are raw assertDelegatedRef(userAfter); - assertJackDummyPirateAccount(); } @@ -938,8 +881,6 @@ public void test161JackAssignRoleSailorValidToRaw() throws Exception { */ @Test public void test162RecomputeJack() throws Exception { - final String TEST_NAME = "test162RecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -979,8 +920,6 @@ public void test162RecomputeJack() throws Exception { */ @Test public void test163Forward15min() throws Exception { - final String TEST_NAME = "test163Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1012,8 +951,6 @@ public void test163Forward15min() throws Exception { */ @Test public void test164JackAssignRoleSailorAgain() throws Exception { - final String TEST_NAME = "test164JackAssignRoleSailorAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1042,7 +979,7 @@ public void test164JackAssignRoleSailorAgain() throws Exception { */ @Test public void test169JackUnassignAll() throws Exception { - unassignAll("test169JackUnassignAll"); + unassignAll(); } /** @@ -1050,8 +987,6 @@ public void test169JackUnassignAll() throws Exception { */ @Test public void test170JackAssignRolePirate() throws Exception { - final String TEST_NAME = "test170JackAssignRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1084,8 +1019,6 @@ public void test170JackAssignRolePirate() throws Exception { */ @Test public void test171JackAssignRoleWeakSingerValidTo() throws Exception { - final String TEST_NAME = "test171JackAssignRoleWeakSingerValidTo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1125,8 +1058,6 @@ public void test171JackAssignRoleWeakSingerValidTo() throws Exception { */ @Test public void test173Forward15min() throws Exception { - final String TEST_NAME = "test173Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1159,8 +1090,6 @@ public void test173Forward15min() throws Exception { */ @Test public void test174JackAssignRoleSingerAgain() throws Exception { - final String TEST_NAME = "test174JackAssignRoleSingerAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1189,7 +1118,7 @@ public void test174JackAssignRoleSingerAgain() throws Exception { */ @Test public void test179JackUnassignAll() throws Exception { - unassignAll("test179JackUnassignAll"); + unassignAll(); } /** @@ -1198,8 +1127,6 @@ public void test179JackUnassignAll() throws Exception { */ @Test public void test180JackAssignRoleSailorValidToRaw() throws Exception { - final String TEST_NAME = "test180JackAssignRoleSailorValidToRaw"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1235,8 +1162,6 @@ public void test180JackAssignRoleSailorValidToRaw() throws Exception { */ @Test public void test182Forward15minAndAssignRaw() throws Exception { - final String TEST_NAME = "test142Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1263,8 +1188,6 @@ public void test182Forward15minAndAssignRaw() throws Exception { */ @Test public void test184RecomputeJack() throws Exception { - final String TEST_NAME = "test184RecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1293,7 +1216,7 @@ public void test184RecomputeJack() throws Exception { */ @Test public void test189JackUnassignAll() throws Exception { - unassignAll("test189JackUnassignAll"); + unassignAll(); } /** @@ -1301,8 +1224,6 @@ public void test189JackUnassignAll() throws Exception { */ @Test public void test200JackAssignCurrentPirateFutureSailor() throws Exception { - final String TEST_NAME = "test200JackAssignCurrentPirateFutureSailor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1337,8 +1258,6 @@ public void test200JackAssignCurrentPirateFutureSailor() throws Exception { */ @Test public void test202RecomputeJack() throws Exception { - final String TEST_NAME = "test202RecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1367,8 +1286,6 @@ public void test202RecomputeJack() throws Exception { */ @Test public void test204ReconcileJack() throws Exception { - final String TEST_NAME = "test204ReconcileJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1394,18 +1311,16 @@ public void test204ReconcileJack() throws Exception { @Test public void test209JackUnassignAll() throws Exception { - unassignAll("test209JackUnassignAll"); + unassignAll(); } /** * The same as test200-204 but with ROLE_STRONG_RICH_SAILOR - * + *

* Preparation for MID-4198 "Disabled assignments project value in certain cases" */ @Test public void test210JackAssignCurrentPirateFutureRichSailor() throws Exception { - final String TEST_NAME = "test210JackAssignCurrentPirateFutureRichSailor"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1440,8 +1355,6 @@ public void test210JackAssignCurrentPirateFutureRichSailor() throws Exception { */ @Test public void test212RecomputeJack() throws Exception { - final String TEST_NAME = "test212RecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1470,8 +1383,6 @@ public void test212RecomputeJack() throws Exception { */ @Test public void test214ReconcileJack() throws Exception { - final String TEST_NAME = "test214ReconcileJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1497,7 +1408,7 @@ public void test214ReconcileJack() throws Exception { @Test public void test219JackUnassignAll() throws Exception { - unassignAll("test219JackUnassignAll"); + unassignAll(); } /** @@ -1505,12 +1416,10 @@ public void test219JackUnassignAll() throws Exception { */ @Test public void test220JackAssignFutureRichSailor() throws Exception { - final String TEST_NAME = "test220JackAssignFutureRichSailor"; - Task task = getTestTask(); OperationResult result = task.getResult(); - unassignAll(TEST_NAME); + unassignAll(); PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); @@ -1539,7 +1448,7 @@ public void test220JackAssignFutureRichSailor() throws Exception { @Test public void test229JackUnassignAll() throws Exception { - unassignAll("test229JackUnassignAll"); + unassignAll(); assertNoDummyAccount(USER_JACK_USERNAME); } @@ -1548,8 +1457,6 @@ public void test229JackUnassignAll() throws Exception { */ @Test public void test230JackAssignRoleStrongRichSailorValidTo() throws Exception { - final String TEST_NAME = "test230JackAssignRoleStrongRichSailorValidTo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1589,11 +1496,8 @@ public void test230JackAssignRoleStrongRichSailorValidTo() throws Exception { /** * Sailor assignment expires. */ - @Test public void test232Forward15min() throws Exception { - final String TEST_NAME = "test232Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1619,7 +1523,7 @@ public void test232Forward15min() throws Exception { @Test public void test239JackUnassignAll() throws Exception { - unassignAll("test239JackUnassignAll"); + unassignAll(); assertNoDummyAccount(USER_JACK_USERNAME); } @@ -1629,8 +1533,6 @@ public void test239JackUnassignAll() throws Exception { */ @Test public void test240JackAssignRoleRichSailorValidTo() throws Exception { - final String TEST_NAME = "test240JackAssignRoleRichSailorValidTo"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1673,8 +1575,6 @@ public void test240JackAssignRoleRichSailorValidTo() throws Exception { @Test public void test242Forward15min() throws Exception { - final String TEST_NAME = "test242Forward15min"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1700,17 +1600,15 @@ public void test242Forward15min() throws Exception { @Test public void test249JackUnassignAll() throws Exception { - unassignAll("test249JackUnassignAll"); + unassignAll(); assertNoDummyAccount(USER_JACK_USERNAME); } /** - * MID-4198 + * MID-4198 */ @Test public void test250JackAssignFocusExistsResource() throws Exception { - final String TEST_NAME = "test250JackAssignFocusExistsResource"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1745,8 +1643,6 @@ public void test250JackAssignFocusExistsResource() throws Exception { */ @Test public void test252RecomputeJack() throws Exception { - final String TEST_NAME = "test252RecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1774,8 +1670,6 @@ public void test252RecomputeJack() throws Exception { */ @Test public void test254ReconcileJack() throws Exception { - final String TEST_NAME = "test254ReconcileJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1798,7 +1692,6 @@ public void test254ReconcileJack() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_FOCUS_EXISTS_NAME, USER_JACK_USERNAME); } - private void assertJackDummyPirateAccount() throws Exception { assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); assertDefaultDummyAccountAttribute(ACCOUNT_JACK_DUMMY_USERNAME, @@ -1875,8 +1768,7 @@ private void assertJackDummyPirateSingerAccount() throws Exception { "Jack Sparrow is the best pirate Caribbean has ever seen"); } - private void unassignAll(final String TEST_NAME) throws Exception { - + private void unassignAll() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1898,6 +1790,4 @@ private void unassignAll(final String TEST_NAME) throws Exception { assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAutoassign.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAutoassign.java index 46a6a598f28..5076a4b7bcd 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAutoassign.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestAutoassign.java @@ -28,7 +28,6 @@ /** * @author semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -80,8 +79,6 @@ public void initSystem(Task initTask, OperationResult initResult) */ @Test public void test100ModifyUnitWorker() throws Exception { - final String TEST_NAME = "test100ModifyUnitWorker"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -113,8 +110,6 @@ public void test100ModifyUnitWorker() throws Exception { */ @Test public void test109ModifyUniNull() throws Exception { - final String TEST_NAME = "test109ModifyUniNull"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -141,8 +136,6 @@ public void test109ModifyUniNull() throws Exception { */ @Test public void test110ModifyUnitSleepwalker() throws Exception { - final String TEST_NAME = "test110ModifyUnitSleepwalker"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -181,8 +174,6 @@ public void test110ModifyUnitSleepwalker() throws Exception { */ @Test public void test112ModifyUnitSleeperToWorker() throws Exception { - final String TEST_NAME = "test112ModifyUnitSleeperToWorker"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -217,8 +208,6 @@ public void test112ModifyUnitSleeperToWorker() throws Exception { */ @Test public void test114ModifyUnitAddSleeper() throws Exception { - final String TEST_NAME = "test114ModifyUnitAddSleeper"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestMetaMeta.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestMetaMeta.java index 7c0dbc41837..c13256e0f6e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestMetaMeta.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestMetaMeta.java @@ -15,10 +15,8 @@ import java.util.HashMap; import java.util.List; import java.util.Map; -import java.util.function.Consumer; import java.util.stream.Collectors; -import com.evolveum.midpoint.test.asserter.prism.PrismObjectAsserter; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -33,24 +31,16 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; +import com.evolveum.midpoint.test.asserter.prism.PrismObjectAsserter; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMetaMeta extends AbstractRbacTest { @@ -74,8 +64,7 @@ public class TestMetaMeta extends AbstractRbacTest { protected static final String GROUP_BETA_NAME = "beta"; protected static final String GROUP_A_NAME = "a"; - protected Map groupRoleOidMap = new HashMap<>(); - + protected Map groupRoleOidMap = new HashMap<>(); // LEGACY @@ -91,7 +80,6 @@ public class TestMetaMeta extends AbstractRbacTest { private String groupOneRoleOid; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { @@ -100,8 +88,6 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test050AddMetaMeta() throws Exception { - final String TEST_NAME = "test050AddMetaMeta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -117,7 +103,7 @@ public void test050AddMetaMeta() throws Exception { new PrismObjectAsserter<>(role).assertSanity(); RoleType roleType = role.asObjectable(); - PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", ROLE_META_META_WORLD_NAME, roleType.getName()); + PrismAsserts.assertEqualsPolyString("Wrong " + role + " name", ROLE_META_META_WORLD_NAME, roleType.getName()); assertAssignments(role, 1); // just direct assignment assertRoleMembershipRef(role /* no values */); @@ -130,13 +116,11 @@ public void test050AddMetaMeta() throws Exception { String groupName = ROLE_META_META_WORLD_NAME.toLowerCase(); DummyGroup dummyGroup = getDummyGroup(null, groupName); - assertNotNull("No dummy group "+groupName, dummyGroup); + assertNotNull("No dummy group " + groupName, dummyGroup); } @Test public void test100AddGreeks() throws Exception { - final String TEST_NAME = "test100AddGreeks"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -153,8 +137,6 @@ public void test100AddGreeks() throws Exception { @Test public void test110AddRomans() throws Exception { - final String TEST_NAME = "test110AddRomans"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -171,8 +153,6 @@ public void test110AddRomans() throws Exception { @Test public void test200CreateAlpha() throws Exception { - final String TEST_NAME = "test200CreateAlpha"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -190,8 +170,6 @@ public void test200CreateAlpha() throws Exception { @Test public void test202CreateBeta() throws Exception { - final String TEST_NAME = "test202CreateBeta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -208,8 +186,6 @@ public void test202CreateBeta() throws Exception { @Test public void test210CreateA() throws Exception { - final String TEST_NAME = "test210CreateA"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -229,8 +205,6 @@ public void test210CreateA() throws Exception { */ @Test public void test300AssignAlphaToJack() throws Exception { - final String TEST_NAME = "test300AssignAlphaToJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -248,8 +222,6 @@ public void test300AssignAlphaToJack() throws Exception { @Test public void test309UnassignAlphaFromJack() throws Exception { - final String TEST_NAME = "test309UnassignAlphaFromJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -276,8 +248,6 @@ public void test309UnassignAlphaFromJack() throws Exception { */ @Test public void test310AssignAToJack() throws Exception { - final String TEST_NAME = "test310AssignAToJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -298,8 +268,6 @@ public void test310AssignAToJack() throws Exception { */ @Test public void test312AssignBetaToJack() throws Exception { - final String TEST_NAME = "test312AssignBetaToJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -317,14 +285,15 @@ public void test312AssignBetaToJack() throws Exception { @Test public void test319UnassignBetaAFromJack() throws Exception { - final String TEST_NAME = "test319UnassignBetaAFromJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); - ObjectDelta focusDelta = createAssignmentFocusDelta(UserType.class, USER_JACK_OID, getGroupRoleOid(GROUP_BETA_NAME), RoleType.COMPLEX_TYPE, null, (Consumer)null, false); - focusDelta.addModification(createAssignmentModification(getGroupRoleOid(GROUP_A_NAME), RoleType.COMPLEX_TYPE, null, null, null, false)); + ObjectDelta focusDelta = createAssignmentFocusDelta( + UserType.class, USER_JACK_OID, getGroupRoleOid(GROUP_BETA_NAME), + RoleType.COMPLEX_TYPE, null, null, false); + focusDelta.addModification(createAssignmentModification( + getGroupRoleOid(GROUP_A_NAME), RoleType.COMPLEX_TYPE, null, null, null, false)); // WHEN modelService.executeChanges(MiscSchemaUtil.createCollection(focusDelta), null, task, result); @@ -347,8 +316,6 @@ public void test319UnassignBetaAFromJack() throws Exception { @Test public void test900LegacyAddMetaMeta() throws Exception { - final String TEST_NAME = "test900LegacyAddMetaMeta"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -364,7 +331,7 @@ public void test900LegacyAddMetaMeta() throws Exception { new PrismObjectAsserter<>(role).assertSanity(); RoleType roleType = role.asObjectable(); - PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", ROLE_META_META_LEGACY_NAME, roleType.getName()); + PrismAsserts.assertEqualsPolyString("Wrong " + role + " name", ROLE_META_META_LEGACY_NAME, roleType.getName()); assertAssignments(role, 1); // just direct assignment assertRoleMembershipRef(role /* no values */); @@ -377,13 +344,11 @@ public void test900LegacyAddMetaMeta() throws Exception { String groupName = ROLE_META_META_LEGACY_NAME.toLowerCase(); DummyGroup dummyGroup = getDummyGroup(null, groupName); - assertNotNull("No dummy group "+groupName, dummyGroup); + assertNotNull("No dummy group " + groupName, dummyGroup); } @Test public void test910LegacyAddMetaLegacyOne() throws Exception { - final String TEST_NAME = "test910LegacyAddMetaLegacyOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -399,7 +364,7 @@ public void test910LegacyAddMetaLegacyOne() throws Exception { new PrismObjectAsserter<>(role).assertSanity(); RoleType roleType = role.asObjectable(); - PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", ROLE_META_LEGACY_ONE_NAME, roleType.getName()); + PrismAsserts.assertEqualsPolyString("Wrong " + role + " name", ROLE_META_LEGACY_ONE_NAME, roleType.getName()); assertAssigned(role, ROLE_META_META_LEGACY_OID, RoleType.COMPLEX_TYPE); assertAssignments(role, 1); @@ -413,20 +378,18 @@ public void test910LegacyAddMetaLegacyOne() throws Exception { String groupName = ROLE_META_LEGACY_ONE_NAME.toLowerCase(); DummyGroup dummyGroup = getDummyGroup(null, groupName); - assertNotNull("No dummy group "+groupName, dummyGroup); + assertNotNull("No dummy group " + groupName, dummyGroup); } @Test public void test920LegacyCreateGroupOne() throws Exception { - final String TEST_NAME = "test920LegacyCreateGroupOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject roleBefore = createObject(RoleType.class, GROUP_ONE_NAME); RoleType roleType = roleBefore.asObjectable(); roleType - .beginAssignment() + .beginAssignment() .targetRef(ROLE_META_LEGACY_ONE_OID, RoleType.COMPLEX_TYPE); // WHEN @@ -435,20 +398,19 @@ public void test920LegacyCreateGroupOne() throws Exception { // THEN assertSuccess(result); - PrismObject roleAfter = getObject(RoleType.class, groupOneRoleOid); display("Role after", roleAfter); new PrismObjectAsserter<>(roleAfter).assertSanity(); RoleType roleTypeAfter = roleAfter.asObjectable(); - PrismAsserts.assertEqualsPolyString("Wrong "+roleAfter+" name", GROUP_ONE_NAME, roleTypeAfter.getName()); + PrismAsserts.assertEqualsPolyString("Wrong " + roleAfter + " name", GROUP_ONE_NAME, roleTypeAfter.getName()); assertAssigned(roleAfter, ROLE_META_LEGACY_ONE_OID, RoleType.COMPLEX_TYPE); assertAssignments(roleAfter, 1); assertRoleMembershipRef(roleAfter, ROLE_META_LEGACY_ONE_OID); DummyGroup dummyGroupOne = getDummyGroup(null, GROUP_ONE_NAME); - assertNotNull("No dummy group "+GROUP_ONE_NAME, dummyGroupOne); + assertNotNull("No dummy group " + GROUP_ONE_NAME, dummyGroupOne); assertLinks(roleAfter, 1); String shadowOid = roleTypeAfter.getLinkRef().get(0).getOid(); @@ -458,8 +420,6 @@ public void test920LegacyCreateGroupOne() throws Exception { @Test public void test930LegacyAssignGroupOneToJack() throws Exception { - final String TEST_NAME = "test930LegacyAssignGroupOneToJack"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -488,8 +448,10 @@ public void test930LegacyAssignGroupOneToJack() throws Exception { } - - private PrismObject readAndAssertGreekGroupMember(String userOid, String... roleNames) throws ConnectException, FileNotFoundException, SchemaViolationException, ConflictException, ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, InterruptedException { + private PrismObject readAndAssertGreekGroupMember(String userOid, String... roleNames) + throws ObjectNotFoundException, ExpressionEvaluationException, SchemaViolationException, + ConflictException, CommunicationException, SchemaException, SecurityViolationException, + ConnectException, ConfigurationException, FileNotFoundException, InterruptedException { PrismObject user = getUser(userOid); display("User after", user); List roleOids = Arrays.stream(roleNames).map(this::getGroupRoleOid).collect(Collectors.toList()); @@ -502,14 +464,13 @@ private PrismObject readAndAssertGreekGroupMember(String userOid, Stri display("User shadow (model)", accountShadow); assertDefaultDummyAccount(user.getName().getOrig(), user.asObjectable().getFullName().getOrig(), true); - for (String roleName: roleNames) { + for (String roleName : roleNames) { assertDummyGroupMember(null, roleName, user.getName().getOrig()); } return user; } - private void rememberGroupRoleOid(String roleName, String roleOid) { groupRoleOidMap.put(roleName, roleOid); } @@ -522,32 +483,36 @@ private void assignGroupRole(String userOid, String roleName, Task task, Operati assignRole(userOid, getGroupRoleOid(roleName), task, result); } - private void unassignGroupRole(String userOid, String roleName, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { + private void unassignGroupRole(String userOid, String roleName, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException { unassignRole(userOid, getGroupRoleOid(roleName), task, result); } - private PrismObject readAndAssertGreekGroupRole(String roleOid, String groupName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { + private PrismObject readAndAssertGreekGroupRole(String roleOid, String groupName) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { return readAndAssertGroupRole(roleOid, ROLE_META_GREEK_GROUP_OID, groupName); } - private PrismObject readAndAssertLatinGroupRole(String roleOid, String groupName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { + private PrismObject readAndAssertLatinGroupRole(String roleOid, String groupName) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { return readAndAssertGroupRole(roleOid, ROLE_META_LATIN_GROUP_OID, groupName); } - private PrismObject readAndAssertGroupRole(String roleOid, String metaroleOid, String groupName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { + private PrismObject readAndAssertGroupRole(String roleOid, String metaroleOid, String groupName) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { PrismObject role = getObject(RoleType.class, roleOid); display("Role after", role); new PrismObjectAsserter<>(role).assertSanity(); RoleType roleType = role.asObjectable(); - PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", groupName, roleType.getName()); + PrismAsserts.assertEqualsPolyString("Wrong " + role + " name", groupName, roleType.getName()); assertAssigned(role, metaroleOid, RoleType.COMPLEX_TYPE); assertAssignments(role, 1); assertRoleMembershipRef(role, metaroleOid); DummyGroup dummyGroup = getDummyGroup(null, groupName); - assertNotNull("No dummy group "+groupName, dummyGroup); + assertNotNull("No dummy group " + groupName, dummyGroup); assertLinks(role, 1); String shadowOid = roleType.getLinkRef().get(0).getOid(); @@ -557,14 +522,15 @@ private PrismObject readAndAssertGroupRole(String roleOid, String meta return role; } - private PrismObject assertMetaRole(String metaroleOid, String metaroleName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { + private PrismObject assertMetaRole(String metaroleOid, String metaroleName) + throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException, SchemaViolationException, ConflictException, InterruptedException { PrismObject role = getObject(RoleType.class, metaroleOid); display("Metarole after", role); new PrismObjectAsserter<>(role).assertSanity(); RoleType roleType = role.asObjectable(); - PrismAsserts.assertEqualsPolyString("Wrong "+role+" name", metaroleName, roleType.getName()); + PrismAsserts.assertEqualsPolyString("Wrong " + role + " name", metaroleName, roleType.getName()); assertAssigned(role, ROLE_META_META_WORLD_OID, RoleType.COMPLEX_TYPE); assertAssignments(role, 1); @@ -578,22 +544,23 @@ private PrismObject assertMetaRole(String metaroleOid, String metarole String groupName = metaroleName.toLowerCase(); DummyGroup dummyGroup = getDummyGroup(null, groupName); - assertNotNull("No dummy group "+groupName, dummyGroup); + assertNotNull("No dummy group " + groupName, dummyGroup); return role; } - - - private String addGreekRole(String roleName, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + private String addGreekRole(String roleName, Task task, OperationResult result) + throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { return addGrupRole(roleName, ROLE_META_GREEK_GROUP_OID, task, result); } - private String addLatinkRole(String roleName, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + private String addLatinkRole(String roleName, Task task, OperationResult result) + throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { return addGrupRole(roleName, ROLE_META_LATIN_GROUP_OID, task, result); } - private String addGrupRole(String roleName, String metaroleOid, Task task, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + private String addGrupRole(String roleName, String metaroleOid, Task task, OperationResult result) + throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { PrismObject role = createGroupRole(roleName, metaroleOid); return addObject(role, task, result); } @@ -601,8 +568,7 @@ private String addGrupRole(String roleName, String metaroleOid, Task task, Opera private PrismObject createGroupRole(String roleName, String metaroleOid) throws SchemaException { PrismObject role = createObject(RoleType.class, roleName); RoleType roleType = role.asObjectable(); - roleType - .beginAssignment() + roleType.beginAssignment() .targetRef(metaroleOid, RoleType.COMPLEX_TYPE); return role; } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java index 93e0cf3e7e8..1d0edaab98b 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java @@ -59,7 +59,6 @@ public class TestRbac extends AbstractRbacTest { private static final String LOCALITY_TORTUGA = "Tortuga"; - private String userLemonheadOid; private String userSharptoothOid; private String userRedskullOid; private String userBignoseOid; @@ -76,8 +75,6 @@ public void initSystem(Task initTask, OperationResult initResult) @Test public void test000SanityRolePirate() throws Exception { - final String TEST_NAME = "test000SanityRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -94,8 +91,6 @@ public void test000SanityRolePirate() throws Exception { @Test public void test001SanityRoleProjectOmnimanager() throws Exception { - final String TEST_NAME = "test001SanityRoleProjectOmnimanager"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -114,8 +109,6 @@ public void test001SanityRoleProjectOmnimanager() throws Exception { @Test public void test010SearchRequestableRoles() throws Exception { - final String TEST_NAME = "test010SearchRequestableRoles"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -134,8 +127,6 @@ public void test010SearchRequestableRoles() throws Exception { @Test public void test101JackAssignRolePirate() throws Exception { - final String TEST_NAME = "test101JackAssignRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -184,8 +175,6 @@ protected ModelExecuteOptions getDefaultOptions() { */ @Test public void test102JackModifyUserLocality() throws Exception { - final String TEST_NAME = "test102JackModifyUserLocality"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -194,8 +183,6 @@ public void test102JackModifyUserLocality() throws Exception { jackDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_GOSSIP_NAME, EXISTING_GOSSIP); - XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - // WHEN modifyUserReplace(USER_JACK_OID, UserType.F_LOCALITY, getDefaultOptions(), task, result, createPolyString(LOCALITY_TORTUGA)); @@ -204,11 +191,9 @@ public void test102JackModifyUserLocality() throws Exception { then(); assertSuccess(result); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - AssignmentType assignmentType = assertAssignedRole(userAfter, ROLE_PIRATE_OID); + assertAssignedRole(userAfter, ROLE_PIRATE_OID); assertRoleMembershipRef(userAfter, ROLE_PIRATE_OID); assertDelegatedRef(userAfter); assertDefaultDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME, ACCOUNT_JACK_DUMMY_FULLNAME, true); @@ -225,8 +210,6 @@ public void test102JackModifyUserLocality() throws Exception { @Test public void test110UnAssignRolePirate() throws Exception { - final String TEST_NAME = "test110UnAssignRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -247,8 +230,6 @@ public void test110UnAssignRolePirate() throws Exception { @Test public void test120JackAssignRolePirateWhileAlreadyHasAccount() throws Exception { - final String TEST_NAME = "test120JackAssignRolePirateWhileAlreadyHasAccount"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -312,8 +293,6 @@ public void test120JackAssignRolePirateWhileAlreadyHasAccount() throws Exception @Test public void test121JackAssignAccountImplicitIntent() throws Exception { - final String TEST_NAME = "test121JackAssignAccountImplicitIntent"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -345,8 +324,6 @@ public void test121JackAssignAccountImplicitIntent() throws Exception { @Test public void test122JackAssignAccountExplicitIntent() throws Exception { - final String TEST_NAME = "test122JackAssignAccountExplicitIntent"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -378,8 +355,6 @@ public void test122JackAssignAccountExplicitIntent() throws Exception { @Test public void test127UnAssignAccountImplicitIntent() throws Exception { - final String TEST_NAME = "test127UnAssignAccountImplicitIntent"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -406,8 +381,6 @@ public void test127UnAssignAccountImplicitIntent() throws Exception { @Test public void test128UnAssignAccountExplicitIntent() throws Exception { - final String TEST_NAME = "test128UnAssignAccountExplicitIntent"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -434,8 +407,6 @@ public void test128UnAssignAccountExplicitIntent() throws Exception { @Test public void test129UnAssignRolePirate() throws Exception { - final String TEST_NAME = "test129UnAssignRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -456,8 +427,6 @@ public void test129UnAssignRolePirate() throws Exception { @Test public void test130JackAssignRolePirateWithSeaInAssignment() throws Exception { - final String TEST_NAME = "test130JackAssignRolePirateWithSeaInAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -493,8 +462,6 @@ public void test130JackAssignRolePirateWithSeaInAssignment() throws Exception { @Test public void test132JackUnAssignRolePirateWithSeaInAssignment() throws Exception { - final String TEST_NAME = "test132JackUnAssignRolePirateWithSeaInAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -525,8 +492,6 @@ public void test132JackUnAssignRolePirateWithSeaInAssignment() throws Exception */ @Test public void test134JackAssignRoleAdriaticPirate() throws Exception { - final String TEST_NAME = "test134JackAssignRoleAdriaticPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -558,8 +523,6 @@ public void test134JackAssignRoleAdriaticPirate() throws Exception { */ @Test public void test135PreviewChangesEmptyDelta() throws Exception { - final String TEST_NAME = "test135PreviewChangesEmptyDelta"; - Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject user = getUser(USER_JACK_OID); @@ -585,13 +548,10 @@ public void test135PreviewChangesEmptyDelta() throws Exception { assertEquals("Wrong number of evaluated role", 2, evaluatedRoles.size()); assertEvaluatedRole(evaluatedRoles, ROLE_ADRIATIC_PIRATE_OID); assertEvaluatedRole(evaluatedRoles, ROLE_PIRATE_OID); - } @Test public void test136JackUnAssignRoleAdriaticPirate() throws Exception { - final String TEST_NAME = "test136JackUnAssignRoleAdriaticPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -616,8 +576,6 @@ public void test136JackUnAssignRoleAdriaticPirate() throws Exception { */ @Test public void test137JackAssignRoleAdriaticPirateWithSeaInAssignment() throws Exception { - final String TEST_NAME = "test137JackAssignRoleAdriaticPirateWithSeaInAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -653,8 +611,6 @@ public void test137JackAssignRoleAdriaticPirateWithSeaInAssignment() throws Exce @Test public void test139JackUnAssignRoleAdriaticPirateWithSeaInAssignment() throws Exception { - final String TEST_NAME = "test139JackUnAssignRoleAdriaticPirateWithSeaInAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -682,8 +638,6 @@ public void test139JackUnAssignRoleAdriaticPirateWithSeaInAssignment() throws Ex @Test public void test144JackAssignRoleBlackSeaPirate() throws Exception { - final String TEST_NAME = "test144JackAssignRoleBlackSeaPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -712,8 +666,6 @@ public void test144JackAssignRoleBlackSeaPirate() throws Exception { @Test public void test146JackUnAssignRoleBlackSeaPirate() throws Exception { - final String TEST_NAME = "test146JackUnAssignRoleBlackSeaPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -734,8 +686,6 @@ public void test146JackUnAssignRoleBlackSeaPirate() throws Exception { @Test public void test147JackAssignRoleBlackSeaPirateWithSeaInAssignment() throws Exception { - final String TEST_NAME = "test147JackAssignRoleBlackSeaPirateWithSeaInAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -772,8 +722,6 @@ public void test147JackAssignRoleBlackSeaPirateWithSeaInAssignment() throws Exce @Test public void test149JackUnAssignRoleBlackSeaPirateWithSeaInAssignment() throws Exception { - final String TEST_NAME = "test149JackUnAssignRoleBlackSeaPirateWithSeaInAssignment"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -801,8 +749,6 @@ public void test149JackUnAssignRoleBlackSeaPirateWithSeaInAssignment() throws Ex @Test public void test154JackAssignRoleIndianOceanPirate() throws Exception { - final String TEST_NAME = "test154JackAssignRoleIndianOceanPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -835,8 +781,6 @@ public void test154JackAssignRoleIndianOceanPirate() throws Exception { @Test public void test156JackUnAssignRoleIndianOceanPirate() throws Exception { - final String TEST_NAME = "test156JackUnAssignRoleIndianOceanPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -861,7 +805,7 @@ public void test156JackUnAssignRoleIndianOceanPirate() throws Exception { */ @Test public void test160JackAssignRolePirateApprover() throws Exception { - testJackAssignRolePirateRelationNoPrivs("test160JackAssignRolePirateApprover", SchemaConstants.ORG_APPROVER); + testJackAssignRolePirateRelationNoPrivs(SchemaConstants.ORG_APPROVER); } /** @@ -869,7 +813,7 @@ public void test160JackAssignRolePirateApprover() throws Exception { */ @Test public void test162JackUnassignRolePirateApprover() throws Exception { - testJackUnassignRolePirateRelationNoPrivs("test160JackAssignRolePirateApprover", SchemaConstants.ORG_APPROVER); + testJackUnassignRolePirateRelationNoPrivs(SchemaConstants.ORG_APPROVER); } @@ -879,7 +823,7 @@ public void test162JackUnassignRolePirateApprover() throws Exception { */ @Test public void test164JackAssignRolePirateOwner() throws Exception { - testJackAssignRolePirateRelationNoPrivs("test164JackAssignRolePirateOwner", SchemaConstants.ORG_OWNER); + testJackAssignRolePirateRelationNoPrivs(SchemaConstants.ORG_OWNER); } /** @@ -887,7 +831,7 @@ public void test164JackAssignRolePirateOwner() throws Exception { */ @Test public void test166JackUnassignRolePirateOwner() throws Exception { - testJackUnassignRolePirateRelationNoPrivs("test166JackUnassignRolePirateOwner", SchemaConstants.ORG_OWNER); + testJackUnassignRolePirateRelationNoPrivs(SchemaConstants.ORG_OWNER); } /** @@ -896,7 +840,7 @@ public void test166JackUnassignRolePirateOwner() throws Exception { */ @Test public void test168JackAssignRolePirateComplicated() throws Exception { - testJackAssignRolePirateRelationNoPrivs("test168JackAssignRolePirateComplicated", RELATION_COMPLICATED_QNAME); + testJackAssignRolePirateRelationNoPrivs(RELATION_COMPLICATED_QNAME); } /** @@ -904,11 +848,10 @@ public void test168JackAssignRolePirateComplicated() throws Exception { */ @Test public void test169JackUnassignRolePirateComplicated() throws Exception { - testJackUnassignRolePirateRelationNoPrivs("test169JackUnassignRolePirateComplicated", RELATION_COMPLICATED_QNAME); + testJackUnassignRolePirateRelationNoPrivs(RELATION_COMPLICATED_QNAME); } - public void testJackAssignRolePirateRelationNoPrivs(final String TEST_NAME, QName relation) throws Exception { - + public void testJackAssignRolePirateRelationNoPrivs(QName relation) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -949,16 +892,13 @@ private void assertJackAssignRolePirateRelationNoPrivs(QName relation) throws Ex assertNoDummyAccount(ACCOUNT_JACK_DUMMY_USERNAME); } - public void testJackUnassignRolePirateRelationNoPrivs(final String TEST_NAME, QName relation) throws Exception { - + public void testJackUnassignRolePirateRelationNoPrivs(QName relation) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUser(USER_JACK_OID); display("User jack before", userBefore); - XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - // WHEN unassignRole(USER_JACK_OID, ROLE_PIRATE_OID, relation, getDefaultOptions(), task, result); @@ -966,7 +906,6 @@ public void testJackUnassignRolePirateRelationNoPrivs(final String TEST_NAME, QN then(); assertSuccess(result); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); assertNoAssignments(userAfter); @@ -983,8 +922,6 @@ public void testJackUnassignRolePirateRelationNoPrivs(final String TEST_NAME, QN */ @Test public void test200ImportRoleAllTreasure() throws Exception { - final String TEST_NAME = "test200ImportRoleAllTreasure"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1005,8 +942,6 @@ public void test200ImportRoleAllTreasure() throws Exception { */ @Test public void test202JackAssignRoleAllTreasure() throws Exception { - final String TEST_NAME = "test202JackAssignRoleAllTreasure"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1038,8 +973,6 @@ public void test202JackAssignRoleAllTreasure() throws Exception { */ @Test public void test204AddGoldTreasureAndRecomputeJack() throws Exception { - final String TEST_NAME = "test204AddGoldTreasureAndRecomputeJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1068,8 +1001,6 @@ public void test204AddGoldTreasureAndRecomputeJack() throws Exception { */ @Test public void test206JackAssignRoleAllLoot() throws Exception { - final String TEST_NAME = "test206JackAssignRoleAllLoot"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1094,8 +1025,6 @@ public void test206JackAssignRoleAllLoot() throws Exception { @Test public void test208JackUnassignRoleAllLoot() throws Exception { - final String TEST_NAME = "test208JackUnassignRoleAllLoot"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1119,8 +1048,6 @@ public void test208JackUnassignRoleAllLoot() throws Exception { @Test public void test209JackUnassignRoleAllTreasure() throws Exception { - final String TEST_NAME = "test209JackUnassignRoleAllTreasure"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1142,8 +1069,6 @@ public void test209JackUnassignRoleAllTreasure() throws Exception { */ @Test(enabled = false) // MID-3966 public void test210JackAssignRoleAllYouCanGet() throws Exception { - final String TEST_NAME = "test210JackAssignRoleAllYouCanGet"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1168,8 +1093,6 @@ public void test210JackAssignRoleAllYouCanGet() throws Exception { @Test(enabled = false) // MID-3966 public void test219JackUnassignRoleAllYouCanGet() throws Exception { - final String TEST_NAME = "test219JackUnassignRoleAllYouCanGet"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1192,8 +1115,6 @@ public void test219JackUnassignRoleAllYouCanGet() throws Exception { @Test public void test501JackAssignRolePirate() throws Exception { - final String TEST_NAME = "test501JackAssignRolePirate"; - // IMPORTANT: Changing the assignment policy assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -1228,8 +1149,6 @@ public void test501JackAssignRolePirate() throws Exception { */ @Test public void test502JackModifyUserLocality() throws Exception { - final String TEST_NAME = "test502JackModifyUserLocality"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1267,8 +1186,6 @@ public void test502JackModifyUserLocality() throws Exception { */ @Test public void test510UnAssignRolePirate() throws Exception { - final String TEST_NAME = "test510UnAssignRolePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1295,8 +1212,6 @@ public void test510UnAssignRolePirate() throws Exception { */ @Test public void test511DeleteAccount() throws Exception { - final String TEST_NAME = "test511DeleteAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1326,8 +1241,6 @@ public void test511DeleteAccount() throws Exception { @Test public void test520JackAssignRolePirate() throws Exception { - final String TEST_NAME = "test520JackAssignRolePirate"; - // IMPORTANT: Changing the assignment policy assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -1358,8 +1271,6 @@ public void test520JackAssignRolePirate() throws Exception { @Test public void test521JackUnassignRolePirateDeleteAccount() throws Exception { - final String TEST_NAME = "test521JackUnassignRolePirateDeleteAccount"; - // IMPORTANT: Changing the assignment policy assumeAssignmentPolicy(AssignmentPolicyEnforcementType.POSITIVE); @@ -1393,7 +1304,6 @@ public void test521JackUnassignRolePirateDeleteAccount() throws Exception { @Test public void test530JackAssignRoleCleric() throws Exception { - final String TEST_NAME = "test530JackAssignRoleCleric"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1410,7 +1320,6 @@ public void test530JackAssignRoleCleric() throws Exception { @Test public void test532JackModifyAssignmentRoleCleric() throws Exception { - final String TEST_NAME = "test532JackModifyAssignmentRoleCleric"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1444,7 +1353,6 @@ public void test532JackModifyAssignmentRoleCleric() throws Exception { @Test public void test539JackUnAssignRoleCleric() throws Exception { - final String TEST_NAME = "test539JackUnAssignRoleCleric"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1480,7 +1388,6 @@ public void test539JackUnAssignRoleCleric() throws Exception { */ @Test public void test540JackAssignRoleWannabe() throws Exception { - final String TEST_NAME = "test540JackAssignRoleWannabe"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1509,7 +1416,6 @@ public void test540JackAssignRoleWannabe() throws Exception { */ @Test public void test541JackRemoveHonorificSuffixWannabe() throws Exception { - final String TEST_NAME = "test541JackRemoveHonorificSuffixWannabe"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1537,7 +1443,6 @@ public void test541JackRemoveHonorificSuffixWannabe() throws Exception { */ @Test public void test542JackModifySubtypeWannabe() throws Exception { - final String TEST_NAME = "test542JackModifySubtypeWannabe"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1566,7 +1471,6 @@ public void test542JackModifySubtypeWannabe() throws Exception { */ @Test public void test543JackRemoveHonorificPrefixWannabe() throws Exception { - final String TEST_NAME = "test543JackRemoveHonorificPrefixWannabe"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1594,7 +1498,6 @@ public void test543JackRemoveHonorificPrefixWannabe() throws Exception { */ @Test public void test544JackSetHonorificSuffixWannabe() throws Exception { - final String TEST_NAME = "test544JackSetHonorificSuffixWannabe"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1625,7 +1528,6 @@ public void test544JackSetHonorificSuffixWannabe() throws Exception { */ @Test public void test545JackRestoreHonorificPrefixWannabe() throws Exception { - final String TEST_NAME = "test545JackRestoreHonorificPrefixWannabe"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1655,7 +1557,6 @@ public void test545JackRestoreHonorificPrefixWannabe() throws Exception { */ @Test public void test549JackUnassignRoleWannabe() throws Exception { - final String TEST_NAME = "test549JackUnassignRoleWannabe"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1680,7 +1581,6 @@ public void test549JackUnassignRoleWannabe() throws Exception { @Test public void test600JackAssignRoleJudge() throws Exception { - final String TEST_NAME = "test600JackAssignRoleJudge"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1716,7 +1616,6 @@ public void test600JackAssignRoleJudge() throws Exception { */ @Test public void test602JackAssignRolePirate() throws Exception { - final String TEST_NAME = "test602JackAssignRolePirate"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1751,7 +1650,6 @@ public void test602JackAssignRolePirate() throws Exception { @Test public void test605JackUnAssignRoleJudgeAssignRolePirate() throws Exception { - final String TEST_NAME = "test605JackUnAssignRoleJudgeAssignRolePirate"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1788,7 +1686,6 @@ public void test605JackUnAssignRoleJudgeAssignRolePirate() throws Exception { @Test public void test609JackUnAssignRolePirate() throws Exception { - final String TEST_NAME = "test609JackUnAssignRolePirate"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1808,7 +1705,6 @@ public void test609JackUnAssignRolePirate() throws Exception { @Test public void test610ElaineAssignRoleGovernor() throws Exception { - final String TEST_NAME = "test610ElaineAssignRoleGovernor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1845,7 +1741,6 @@ public void test610ElaineAssignRoleGovernor() throws Exception { */ @Test public void test612JackAssignRoleGovernor() throws Exception { - final String TEST_NAME = "test612JackAssignRoleGovernor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1876,12 +1771,10 @@ public void test612JackAssignRoleGovernor() throws Exception { */ @Test public void test613JackAssignRoleGovernorAsApprover() throws Exception { - if (!testMultiplicityConstraintsForNonDefaultRelations()) { return; } - final String TEST_NAME = "test613JackAssignRoleGovernorAsApprover"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1914,7 +1807,6 @@ public void test613JackAssignRoleGovernorAsApprover() throws Exception { */ @Test public void test620LemonheadAssignRoleCanibal() throws Exception { - final String TEST_NAME = "test620LemonheadAssignRoleCanibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1922,7 +1814,6 @@ public void test620LemonheadAssignRoleCanibal() throws Exception { PrismObject user = createUser(USER_LEMONHEAD_NAME, USER_LEMONHEAD_FULLNAME, true); addObject(user); - userLemonheadOid = user.getOid(); assertAssignees(ROLE_CANNIBAL_OID, 0); @@ -1944,7 +1835,6 @@ public void test620LemonheadAssignRoleCanibal() throws Exception { @Test public void test622SharptoothAssignRoleCanibal() throws Exception { - final String TEST_NAME = "test622SharptoothAssignRoleCanibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -1974,7 +1864,6 @@ public void test622SharptoothAssignRoleCanibal() throws Exception { @Test public void test624RedskullAssignRoleCanibal() throws Exception { - final String TEST_NAME = "test624RedskullAssignRoleCanibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2004,7 +1893,6 @@ public void test624RedskullAssignRoleCanibal() throws Exception { @Test public void test625BignoseAssignRoleCanibal() throws Exception { - final String TEST_NAME = "test625BignoseAssignRoleCanibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2040,7 +1928,6 @@ public void test625BignoseAssignRoleCanibal() throws Exception { @Test public void test627SharptoothUnassignRoleCanibal() throws Exception { - final String TEST_NAME = "test627SharptoothUnassignRoleCanibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2065,7 +1952,6 @@ public void test627SharptoothUnassignRoleCanibal() throws Exception { @Test public void test628RedskullUnassignRoleCanibal() throws Exception { - final String TEST_NAME = "test628RedskullUnassignRoleCanibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2104,7 +1990,6 @@ public void test630RappAssignRoleCannibalAsOwner() throws Exception { return; } - final String TEST_NAME = "test630RappAssignRoleCannibalAsOwner"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2133,7 +2018,6 @@ public void test632RappUnassignRoleCannibalAsOwner() throws Exception { return; } - final String TEST_NAME = "test632RappUnassignRoleCannibalAsOwner"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2173,7 +2057,6 @@ public void test634BignoseAssignRoleCannibalAsOwner() throws Exception { return; } - final String TEST_NAME = "test634BignoseAssignRoleCannibalAsOwner"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2208,7 +2091,6 @@ public void test636BignoseUnassignRoleCannibalAsOwner() throws Exception { return; } - final String TEST_NAME = "test636BignoseUnassignRoleCannibalAsOwner"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2234,7 +2116,6 @@ public void test636BignoseUnassignRoleCannibalAsOwner() throws Exception { @Test public void test649ElaineUnassignRoleGovernor() throws Exception { - final String TEST_NAME = "test649ElaineUnassignRoleGovernor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2262,7 +2143,6 @@ public void test649ElaineUnassignRoleGovernor() throws Exception { @Test public void test650BignoseAssignRoleCannibalAsOwner() throws Exception { - final String TEST_NAME = "test650BignoseAssignRoleCannibalAsOwner"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); assertUserBefore(userBignoseOid) @@ -2288,7 +2168,6 @@ public void test650BignoseAssignRoleCannibalAsOwner() throws Exception { @Test public void test651BignoseAssignRoleCannibalAsApprover() throws Exception { - final String TEST_NAME = "test651BignoseAssignRoleCannibalAsApprover"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2314,7 +2193,6 @@ public void test651BignoseAssignRoleCannibalAsApprover() throws Exception { */ @Test public void test655BignoseAssignRoleCannibal() throws Exception { - final String TEST_NAME = "test655BignoseAssignRoleCannibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2338,7 +2216,6 @@ public void test655BignoseAssignRoleCannibal() throws Exception { @Test public void test656BignoseUnassignRoleCannibal() throws Exception { - final String TEST_NAME = "test656BignoseUnassignRoleCannibal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2361,7 +2238,6 @@ public void test656BignoseUnassignRoleCannibal() throws Exception { @Test public void test658BignoseUnassignRoleCannibalAsOwner() throws Exception { - final String TEST_NAME = "test658BignoseUnassignRoleCannibalAsOwner"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Task task = getTestTask(); @@ -2387,7 +2263,6 @@ public void test658BignoseUnassignRoleCannibalAsOwner() throws Exception { @Test public void test700JackAssignRoleJudge() throws Exception { - final String TEST_NAME = "test700JackModifyJudgeRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2412,7 +2287,6 @@ public void test700JackAssignRoleJudge() throws Exception { @Test public void test701JackModifyJudgeDeleteConstructionRecompute() throws Exception { - final String TEST_NAME = "test701JackModifyJudgeDeleteConstructionRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2442,7 +2316,6 @@ public void test701JackModifyJudgeDeleteConstructionRecompute() throws Exception @Test public void test702JackModifyJudgeAddInducementHonorabilityRecompute() throws Exception { - final String TEST_NAME = "test702JackModifyJudgeAddInducementHonorabilityRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2477,7 +2350,6 @@ public void test702JackModifyJudgeAddInducementHonorabilityRecompute() throws Ex @Test public void test703JackModifyJudgeDeleteInducementHonorabilityRecompute() throws Exception { - final String TEST_NAME = "test703JackModifyJudgeDeleteInducementHonorabilityRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2512,7 +2384,6 @@ public void test703JackModifyJudgeDeleteInducementHonorabilityRecompute() throws @Test public void test709JackUnAssignRoleJudge() throws Exception { - final String TEST_NAME = "test709JackUnAssignRoleJudge"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2536,7 +2407,6 @@ public void test709JackUnAssignRoleJudge() throws Exception { @Test public void test710JackAssignRoleEmpty() throws Exception { - final String TEST_NAME = "test710JackAssignRoleEmpty"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2561,7 +2431,6 @@ public void test710JackAssignRoleEmpty() throws Exception { @Test public void test712JackModifyEmptyRoleAddInducementPirateRecompute() throws Exception { - final String TEST_NAME = "test712JackModifyEmptyRoleAddInducementPirateRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2593,7 +2462,6 @@ public void test712JackModifyEmptyRoleAddInducementPirateRecompute() throws Exce @Test public void test714JackModifyEmptyRoleDeleteInducementPirateRecompute() throws Exception { - final String TEST_NAME = "test714JackModifyEmptyRoleDeleteInducementPirateRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2620,7 +2488,6 @@ public void test714JackModifyEmptyRoleDeleteInducementPirateRecompute() throws E @Test public void test719JackUnAssignRoleEmpty() throws Exception { - final String TEST_NAME = "test719JackUnAssignRoleEmpty"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2644,7 +2511,6 @@ public void test719JackUnAssignRoleEmpty() throws Exception { @Test public void test720JackAssignRoleGovernorTenantRef() throws Exception { - final String TEST_NAME = "test720JackAssignRoleGovernorTenantRef"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2675,7 +2541,6 @@ public void test720JackAssignRoleGovernorTenantRef() throws Exception { @Test public void test729JackUnassignRoleGovernorTenantRef() throws Exception { - final String TEST_NAME = "test729JackUnassignRoleGovernorTenantRef"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2707,7 +2572,6 @@ public void test729JackUnassignRoleGovernorTenantRef() throws Exception { */ @Test public void test750JackAssignRoleOmnimanager() throws Exception { - final String TEST_NAME = "test750JackAssignRoleOmnimanager"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2738,7 +2602,6 @@ public void test750JackAssignRoleOmnimanager() throws Exception { */ @Test public void test755AddProjectAndRecomputeJack() throws Exception { - final String TEST_NAME = "test755AddProjectAndRecomputeJack"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2773,7 +2636,6 @@ public void test755AddProjectAndRecomputeJack() throws Exception { */ @Test public void test759JackUnassignRoleOmnimanager() throws Exception { - final String TEST_NAME = "test759JackUnassignRoleOmnimanager"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2804,7 +2666,6 @@ public void test759JackUnassignRoleOmnimanager() throws Exception { */ @Test public void test760JackAssignRoleWeakGossiper() throws Exception { - final String TEST_NAME = "test760JackAssignRoleWeakGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2840,7 +2701,6 @@ public void test760JackAssignRoleWeakGossiper() throws Exception { */ @Test public void test761JackRecompute() throws Exception { - final String TEST_NAME = "test761JackRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2873,7 +2733,6 @@ public void test761JackRecompute() throws Exception { */ @Test public void test762JackReconcile() throws Exception { - final String TEST_NAME = "test762JackReconcile"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -2906,8 +2765,6 @@ public void test762JackReconcile() throws Exception { */ @Test public void test763PreviewChanges() throws Exception { - final String TEST_NAME = "test763PreviewChanges"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2965,7 +2822,6 @@ public void test763PreviewChanges() throws Exception { */ @Test public void test764JackAssignRoleSailor() throws Exception { - final String TEST_NAME = "test764JackAssignRoleSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3004,7 +2860,6 @@ public void test764JackAssignRoleSailor() throws Exception { */ @Test public void test765JackRecompute() throws Exception { - final String TEST_NAME = "test765JackRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3042,7 +2897,6 @@ public void test765JackRecompute() throws Exception { */ @Test public void test766JackReconcile() throws Exception { - final String TEST_NAME = "test766JackReconcile"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3082,7 +2936,6 @@ public void test766JackReconcile() throws Exception { */ @Test public void test767JackUnAssignRoleWeakGossiper() throws Exception { - final String TEST_NAME = "test767JackUnAssignRoleWeakGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3119,7 +2972,6 @@ public void test767JackUnAssignRoleWeakGossiper() throws Exception { */ @Test public void test768JackRecompute() throws Exception { - final String TEST_NAME = "test768JackRecompute"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3156,7 +3008,6 @@ public void test768JackRecompute() throws Exception { */ @Test public void test769JackUnAssignRoleSailor() throws Exception { - final String TEST_NAME = "test762JackAssignRoleSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3190,7 +3041,6 @@ public void test769JackUnAssignRoleSailor() throws Exception { */ @Test public void test770JackAssignRoleSailor() throws Exception { - final String TEST_NAME = "test770JackAssignRoleSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3229,7 +3079,6 @@ public void test770JackAssignRoleSailor() throws Exception { */ @Test public void test772JackAssignRoleGossiper() throws Exception { - final String TEST_NAME = "test772JackAssignRoleGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3269,7 +3118,6 @@ public void test772JackAssignRoleGossiper() throws Exception { */ @Test public void test774JackUnAssignRoleSailor() throws Exception { - final String TEST_NAME = "test774JackUnAssignRoleSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3303,7 +3151,6 @@ public void test774JackUnAssignRoleSailor() throws Exception { */ @Test public void test775JackUnAssignRoleGossiper() throws Exception { - final String TEST_NAME = "test775JackUnAssignRoleGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3337,7 +3184,6 @@ public void test775JackUnAssignRoleGossiper() throws Exception { */ @Test public void test778JackAssignRoleGossiperAndSailor() throws Exception { - final String TEST_NAME = "test778JackAssignRoleGossiperAndSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3382,7 +3228,6 @@ public void test778JackAssignRoleGossiperAndSailor() throws Exception { */ @Test public void test779JackUnassignRoleGossiperAndSailor() throws Exception { - final String TEST_NAME = "test779JackUnassignRoleGossiperAndSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3421,7 +3266,6 @@ public void test779JackUnassignRoleGossiperAndSailor() throws Exception { */ @Test public void test780JackAssignRoleWeakSinger() throws Exception { - final String TEST_NAME = "test780JackAssignRoleWeakSinger"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3458,7 +3302,6 @@ public void test780JackAssignRoleWeakSinger() throws Exception { */ @Test public void test781JackAssignRoleWeakGossiper() throws Exception { - final String TEST_NAME = "test781JackAssignRoleWeakGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3495,7 +3338,6 @@ public void test781JackAssignRoleWeakGossiper() throws Exception { */ @Test public void test782JackAssignRoleSailor() throws Exception { - final String TEST_NAME = "test782JackAssignRoleSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3537,7 +3379,6 @@ public void test782JackAssignRoleSailor() throws Exception { */ @Test public void test783JackUnassignRoleSailor() throws Exception { - final String TEST_NAME = "test783JackUnassignRoleSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3571,7 +3412,6 @@ public void test783JackUnassignRoleSailor() throws Exception { */ @Test public void test784JackUnAssignRoleWeakSinger() throws Exception { - final String TEST_NAME = "test784JackUnAssignRoleWeakSinger"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3607,7 +3447,6 @@ public void test784JackUnAssignRoleWeakSinger() throws Exception { */ @Test public void test785JackUnAssignRoleGossiper() throws Exception { - final String TEST_NAME = "test785JackUnAssignRoleGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3641,7 +3480,6 @@ public void test785JackUnAssignRoleGossiper() throws Exception { */ @Test public void test786JackAssignRoleGossiperAndSinger() throws Exception { - final String TEST_NAME = "test786JackAssignRoleGossiperAndSinger"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3681,7 +3519,6 @@ public void test786JackAssignRoleGossiperAndSinger() throws Exception { */ @Test public void test788JackUnassignRoleGossiperAndSinger() throws Exception { - final String TEST_NAME = "test788JackUnassignRoleGossiperAndSinger"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3721,7 +3558,6 @@ public void test788JackUnassignRoleGossiperAndSinger() throws Exception { */ @Test public void test790JackAssignRoleWeakSinger() throws Exception { - final String TEST_NAME = "test780JackAssignRoleWeakSinger"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3760,7 +3596,6 @@ public void test790JackAssignRoleWeakSinger() throws Exception { */ @Test public void test791JackSwitchRolesGossiperAndSinger() throws Exception { - final String TEST_NAME = "test791JackSwitchRolesGossiperAndSinger"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3802,7 +3637,6 @@ public void test791JackSwitchRolesGossiperAndSinger() throws Exception { */ @Test public void test792JackAssignRoleSailor() throws Exception { - final String TEST_NAME = "test792JackAssignRoleSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3846,7 +3680,6 @@ public void test792JackAssignRoleSailor() throws Exception { */ @Test public void test793JackSwitchRolesSingerAndGossiper() throws Exception { - final String TEST_NAME = "test793JackSwitchRolesSingerAndGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3892,7 +3725,6 @@ public void test793JackSwitchRolesSingerAndGossiper() throws Exception { */ @Test public void test794JackSwitchRolesSailorAndGossiper() throws Exception { - final String TEST_NAME = "test793JackSwitchRolesSingerAndGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3932,7 +3764,6 @@ public void test794JackSwitchRolesSailorAndGossiper() throws Exception { */ @Test public void test795JackSwitchRolesSingerAndSailor() throws Exception { - final String TEST_NAME = "test795JackSwitchRolesSingerAndSailor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -3978,7 +3809,6 @@ public void test795JackSwitchRolesSingerAndSailor() throws Exception { */ @Test public void test796JackSwitchRolesSailorAndGovernor() throws Exception { - final String TEST_NAME = "test796JackSwitchRolesSailorAndGovernor"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4025,7 +3855,6 @@ public void test796JackSwitchRolesSailorAndGovernor() throws Exception { */ @Test public void test799JackUnassignGovernorAndWeakGossiper() throws Exception { - final String TEST_NAME = "test799JackUnassignGovernorAndWeakGossiper"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4060,7 +3889,6 @@ public void test799JackUnassignGovernorAndWeakGossiper() throws Exception { @Test public void test800ModifyRoleImmutable() throws Exception { - final String TEST_NAME = "test800ModifyRoleImmutable"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4090,7 +3918,6 @@ public void test800ModifyRoleImmutable() throws Exception { */ @Test public void test802AddGlobalImmutableRole() throws Exception { - final String TEST_NAME = "test802AddGlobalImmutableRole"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4115,7 +3942,6 @@ public void test802AddGlobalImmutableRole() throws Exception { @Test public void test804ModifyRoleImmutableGlobalIdentifier() throws Exception { - final String TEST_NAME = "test804ModifyRoleImmutableGlobalIdentifier"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4142,7 +3968,6 @@ public void test804ModifyRoleImmutableGlobalIdentifier() throws Exception { @Test public void test805ModifyRoleImmutableGlobalDescription() throws Exception { - final String TEST_NAME = "test805ModifyRoleImmutableGlobalDescription"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4173,7 +3998,6 @@ public void test805ModifyRoleImmutableGlobalDescription() throws Exception { */ @Test public void test812AddGlobalImmutableDescriptionRole() throws Exception { - final String TEST_NAME = "test812AddGlobalImmutableDescriptionRole"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4201,7 +4025,6 @@ public void test812AddGlobalImmutableDescriptionRole() throws Exception { */ @Test public void test814ModifyRoleImmutableDescriptionGlobalIdentifier() throws Exception { - final String TEST_NAME = "test814ModifyRoleImmutableDescriptionGlobalIdentifier"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4225,7 +4048,6 @@ public void test814ModifyRoleImmutableDescriptionGlobalIdentifier() throws Excep @Test public void test815ModifyRoleImmutableGlobalDescription() throws Exception { - final String TEST_NAME = "test815ModifyRoleImmutableGlobalDescription"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4251,7 +4073,6 @@ public void test815ModifyRoleImmutableGlobalDescription() throws Exception { @Test public void test826AddNonCreateableRole() throws Exception { - final String TEST_NAME = "test826AddNonCreateableRole"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4278,7 +4099,6 @@ public void test826AddNonCreateableRole() throws Exception { @Test public void test826bAddCreateableRole() throws Exception { - final String TEST_NAME = "test826bAddCreateableRole"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4302,7 +4122,6 @@ public void test826bAddCreateableRole() throws Exception { */ @Test public void test827AddImmutableAssignRole() throws Exception { - final String TEST_NAME = "test827AddImmutableAssignRole"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4334,7 +4153,6 @@ public void test827AddImmutableAssignRole() throws Exception { */ @Test public void test828ModifyUntouchableMetarole() throws Exception { - final String TEST_NAME = "test828ModifyUntouchableMetarole"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4356,7 +4174,6 @@ public void test828ModifyUntouchableMetarole() throws Exception { @Test public void test830ModifyRoleJudge() throws Exception { - final String TEST_NAME = "test830ModifyRoleJudge"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4378,7 +4195,6 @@ public void test830ModifyRoleJudge() throws Exception { @Test public void test840AssignRoleNonAssignable() throws Exception { - final String TEST_NAME = "test840AssignRoleNonAssignable"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4408,7 +4224,6 @@ public void test840AssignRoleNonAssignable() throws Exception { @Test public void test850JackAssignRoleBloodyFool() throws Exception { - final String TEST_NAME = "test850JackAssignRoleBloodyFool"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4445,7 +4260,6 @@ public void test850JackAssignRoleBloodyFool() throws Exception { @Test public void test855JackModifyFoolMetaroleDeleteInducement() throws Exception { - final String TEST_NAME = "test855JackModifyFoolMetaroleDeleteInducement"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4472,7 +4286,6 @@ public void test855JackModifyFoolMetaroleDeleteInducement() throws Exception { @Test public void test857JackReconcile() throws Exception { - final String TEST_NAME = "test857JackReconcile"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4512,7 +4325,6 @@ public void test857JackReconcile() throws Exception { @Test public void test870AssignRoleScreaming() throws Exception { - final String TEST_NAME = "test870AssignRoleScreaming"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); notificationManager.setDisabled(false); @@ -4549,7 +4361,6 @@ public void test870AssignRoleScreaming() throws Exception { */ @Test public void test880GlobalRuleOnChange() throws Exception { - final String TEST_NAME = "test880GlobalRuleOnChange"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4570,7 +4381,6 @@ public void test880GlobalRuleOnChange() throws Exception { @Test(enabled = false) // MID-4856 public void test890DeleteRoleUndeletable() throws Exception { - final String TEST_NAME = "test890DeleteRoleUndeletable"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4591,7 +4401,6 @@ public void test890DeleteRoleUndeletable() throws Exception { @Test // MID-4856 public void test892DeleteRoleUndeletableGlobal() throws Exception { - final String TEST_NAME = "test892DeleteRoleUndeletableGlobal"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); @@ -4613,7 +4422,6 @@ public void test892DeleteRoleUndeletableGlobal() throws Exception { @Test public void test900ModifyDetectingRole() throws Exception { - final String TEST_NAME = "test900ModifyDetectingRole"; assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); Task task = getTestTask(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java index 3366ff02c13..86961bb28dd 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestSegregationOfDuties.java @@ -14,54 +14,35 @@ import java.util.List; import java.util.function.Consumer; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; import org.testng.annotations.Test; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignment; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignmentTarget; -import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRule; -import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRuleTrigger; -import com.evolveum.midpoint.model.api.context.ModelContext; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.model.api.context.*; import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.DeltaSetTriple; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismAsserts; +import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.GlobalPolicyRuleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyActionsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyConstraintKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PolicyExceptionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSegregationOfDuties extends AbstractInitializedModelIntegrationTest { @@ -87,12 +68,10 @@ public class TestSegregationOfDuties extends AbstractInitializedModelIntegration protected static final String ROLE_PRIZE_BRONZE_OID = "19f11686-df22-11e6-b0e9-835ed7ca08a5"; protected static final String ROLE_PRIZE_BRONZE_SHIP = "Bronze"; protected static final File ROLE_PRIZE_BRONZE_ENFORCED_FILE = new File(TEST_DIR, "role-prize-bronze-enforced.xml"); - protected static final String ROLE_PRIZE_BRONZE_ENFORCED_OID = "702dc3c9-9755-4880-b132-cf82d5845dd9"; // Red, green and blue: mutual exclusion (prune) in the metarole protected static final File ROLE_META_COLOR_FILE = new File(TEST_DIR, "role-meta-color.xml"); - protected static final String ROLE_META_COLOR_OID = "0b759ce2-df29-11e6-a84c-9b213183a815"; protected static final File ROLE_COLOR_RED_FILE = new File(TEST_DIR, "role-color-red.xml"); protected static final String ROLE_COLOR_RED_OID = "eaa4ec3e-df28-11e6-9cca-336e0346d5cc"; @@ -112,7 +91,6 @@ public class TestSegregationOfDuties extends AbstractInitializedModelIntegration // Executive / controlling exclusion roles protected static final File ROLE_META_EXECUTIVE_FILE = new File(TEST_DIR, "role-meta-executive.xml"); - protected static final String ROLE_META_EXECUTIVE_OID = "d20aefe6-3ecf-11e7-8068-5f346db1ee00"; protected static final File ROLE_EXECUTIVE_1_FILE = new File(TEST_DIR, "role-executive-1.xml"); protected static final String ROLE_EXECUTIVE_1_OID = "d20aefe6-3ecf-11e7-8068-5f346db1ee01"; @@ -121,7 +99,6 @@ public class TestSegregationOfDuties extends AbstractInitializedModelIntegration protected static final String ROLE_EXECUTIVE_2_OID = "d20aefe6-3ecf-11e7-8068-5f346db1ee02"; protected static final File ROLE_META_CONTROLLING_FILE = new File(TEST_DIR, "role-meta-controlling.xml"); - protected static final String ROLE_META_CONTROLLING_OID = "d20aefe6-3ecf-11e7-8068-5f346db1cc00"; protected static final File ROLE_CONTROLLING_1_FILE = new File(TEST_DIR, "role-controlling-1.xml"); protected static final String ROLE_CONTROLLING_1_OID = "d20aefe6-3ecf-11e7-8068-5f346db1cc01"; @@ -186,8 +163,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test110SimpleExclusion1() throws Exception { - final String TEST_NAME = "test110SimpleExclusion1"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -218,8 +193,6 @@ public void test110SimpleExclusion1() throws Exception { */ @Test public void test120SimpleExclusion2() throws Exception { - final String TEST_NAME = "test120SimpleExclusion2"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -242,12 +215,10 @@ public void test120SimpleExclusion2() throws Exception { @Test public void test130SimpleExclusionBoth1() throws Exception { - final String TEST_NAME = "test130SimpleExclusionBoth1"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -266,12 +237,10 @@ public void test130SimpleExclusionBoth1() throws Exception { @Test public void test140SimpleExclusionBoth2() throws Exception { - final String TEST_NAME = "test140SimpleExclusionBoth2"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -290,12 +259,10 @@ public void test140SimpleExclusionBoth2() throws Exception { @Test public void test150SimpleExclusionBothBidirectional1() throws Exception { - final String TEST_NAME = "test150SimpleExclusionBothBidirectional1"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_THIEF_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -314,12 +281,10 @@ public void test150SimpleExclusionBothBidirectional1() throws Exception { @Test public void test160SimpleExclusionBothBidirectional2() throws Exception { - final String TEST_NAME = "test160SimpleExclusionBothBidirectional2"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); modifications.add((createAssignmentModification(ROLE_THIEF_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -338,8 +303,6 @@ public void test160SimpleExclusionBothBidirectional2() throws Exception { @Test public void test171SimpleExclusion1WithPolicyException() throws Exception { - final String TEST_NAME = "test171SimpleExclusion1WithPolicyException"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -359,8 +322,6 @@ public void test171SimpleExclusion1WithPolicyException() throws Exception { @Test public void test172SimpleExclusion2WithPolicyException() throws Exception { - final String TEST_NAME = "test172SimpleExclusion2WithPolicyException"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -380,8 +341,6 @@ public void test172SimpleExclusion2WithPolicyException() throws Exception { @Test public void test173SimpleExclusion3WithPolicyException() throws Exception { - final String TEST_NAME = "test173SimpleExclusion3WithPolicyException"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -401,8 +360,6 @@ public void test173SimpleExclusion3WithPolicyException() throws Exception { @Test public void test174SimpleExclusion4WithPolicyException() throws Exception { - final String TEST_NAME = "test174SimpleExclusion4WithPolicyException"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -427,8 +384,6 @@ public void test174SimpleExclusion4WithPolicyException() throws Exception { */ @Test public void test180JudgeExceptionalPirateAndThief() throws Exception { - final String TEST_NAME = "test180JudgeExceptionalPirateAndThief"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -466,12 +421,10 @@ private Consumer getJudgeExceptionBlock(String excludedRoleName) @Test public void test190DifferentRelations() throws Exception { - final String TEST_NAME = "test190DifferentRelations"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, SchemaConstants.ORG_APPROVER, null, null, true))); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, null, null, null, true))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -489,12 +442,10 @@ public void test190DifferentRelations() throws Exception { @Test public void test193BothRelationsApprover() throws Exception { - final String TEST_NAME = "test193BothRelationsApprover"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, SchemaConstants.ORG_APPROVER, null, null, true))); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, SchemaConstants.ORG_APPROVER, null, null, true))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -512,12 +463,10 @@ public void test193BothRelationsApprover() throws Exception { @Test public void test194MemberAndManager() throws Exception { - final String TEST_NAME = "test194MemberAndManager"; - Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add((createAssignmentModification(ROLE_JUDGE_OID, RoleType.COMPLEX_TYPE, SchemaConstants.ORG_MANAGER, null, null, true))); modifications.add((createAssignmentModification(ROLE_PIRATE_OID, RoleType.COMPLEX_TYPE, SchemaConstants.ORG_DEFAULT, null, null, true))); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -542,8 +491,6 @@ public void test194MemberAndManager() throws Exception { */ @Test public void test200GuybrushAssignRoleGold() throws Exception { - final String TEST_NAME = "test200GuybrushAssignRoleGold"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -575,8 +522,6 @@ public void test200GuybrushAssignRoleGold() throws Exception { */ @Test public void test202GuybrushAssignRoleSilver() throws Exception { - final String TEST_NAME = "test202GuybrushAssignRoleSilver"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -609,8 +554,6 @@ public void test202GuybrushAssignRoleSilver() throws Exception { */ @Test public void test204GuybrushAssignRoleSailor() throws Exception { - final String TEST_NAME = "test204GuybrushAssignRoleSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -638,14 +581,11 @@ public void test204GuybrushAssignRoleSailor() throws Exception { DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, RESOURCE_DUMMY_DRINK, ROLE_SAILOR_DRINK); } - /** * MID-3685 */ @Test public void test206GuybrushAssignRoleBronze() throws Exception { - final String TEST_NAME = "test206GuybrushAssignRoleBronze"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -678,8 +618,6 @@ public void test206GuybrushAssignRoleBronze() throws Exception { */ @Test public void test208GuybrushUnassignRoleBronze() throws Exception { - final String TEST_NAME = "test208GuybrushUnassignRoleSilver"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -710,8 +648,6 @@ public void test208GuybrushUnassignRoleBronze() throws Exception { */ @Test public void test209GuybrushUnassignRoleSailor() throws Exception { - final String TEST_NAME = "test209GuybrushUnassignRoleSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -735,13 +671,11 @@ public void test209GuybrushUnassignRoleSailor() throws Exception { /** * There's an inherent conflict on resource attribute preventing the two roles to be assigned at once. * Original enforcement hook reacted too late so the "Attempt to replace 2 values to a single-valued item" comes first. - * + *

* MID-4797 */ @Test public void test209aGuybrushAssignRoleGoldAndSilverEnforced() throws Exception { - final String TEST_NAME = "test209aGuybrushAssignRoleGoldAndSilverEnforced"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -772,8 +706,6 @@ public void test209aGuybrushAssignRoleGoldAndSilverEnforced() throws Exception { */ @Test public void test209bGuybrushAssignRoleGoldAndSilver() throws Exception { - final String TEST_NAME = "test209bGuybrushAssignRoleGoldAndSilver"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -804,8 +736,6 @@ public void test209bGuybrushAssignRoleGoldAndSilver() throws Exception { */ @Test public void test210GuybrushAssignRoleRed() throws Exception { - final String TEST_NAME = "test210GuybrushAssignRoleRed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -835,8 +765,6 @@ public void test210GuybrushAssignRoleRed() throws Exception { */ @Test public void test212GuybrushAssignRoleGreen() throws Exception { - final String TEST_NAME = "test212GuybrushAssignRoleGreen"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -867,8 +795,6 @@ public void test212GuybrushAssignRoleGreen() throws Exception { */ @Test public void test214GuybrushAssignRoleColorNone() throws Exception { - final String TEST_NAME = "test214GuybrushAssignRoleColorNone"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -897,8 +823,6 @@ public void test214GuybrushAssignRoleColorNone() throws Exception { */ @Test public void test216GuybrushAssignRoleBlue() throws Exception { - final String TEST_NAME = "test216GuybrushAssignRoleBlue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -926,8 +850,6 @@ public void test216GuybrushAssignRoleBlue() throws Exception { @Test public void test219GuybrushUnassignRoleBlue() throws Exception { - final String TEST_NAME = "test219GuybrushUnassignRoleBlue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -953,8 +875,6 @@ public void test219GuybrushUnassignRoleBlue() throws Exception { @Test public void test220GuybrushAssignRoleBlue() throws Exception { - final String TEST_NAME = "test220GuybrushAssignRoleBlue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -985,8 +905,6 @@ public void test220GuybrushAssignRoleBlue() throws Exception { */ @Test public void test221GuybrushDestroyAndRecompute() throws Exception { - final String TEST_NAME = "test221GuybrushDestroyAndRecompute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1025,8 +943,6 @@ public void test221GuybrushDestroyAndRecompute() throws Exception { */ @Test public void test222GuybrushDestroyAndAssignRoleRed() throws Exception { - final String TEST_NAME = "test222GuybrushDestroyAndAssignRoleRed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1053,7 +969,7 @@ public void test222GuybrushDestroyAndAssignRoleRed() throws Exception { assertNotAssignedRole(userAfter, ROLE_COLOR_BLUE_OID); assertNotAssignedRole(userAfter, ROLE_COLOR_NONE_OID); - String shadowAfterOid = getSingleLinkOid(userAfter); + getSingleLinkOid(userAfter); assertDummyAccount(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME); assertDummyAccountAttribute(null, ACCOUNT_GUYBRUSH_DUMMY_USERNAME, @@ -1062,8 +978,6 @@ public void test222GuybrushDestroyAndAssignRoleRed() throws Exception { @Test public void test229GuybrushUnassignRoleRed() throws Exception { - final String TEST_NAME = "test229GuybrushUnassignRoleRed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1092,8 +1006,6 @@ public void test229GuybrushUnassignRoleRed() throws Exception { */ @Test public void test230GuybrushAssignRoleRedAndBlueAndGreen() throws Exception { - final String TEST_NAME = "test230GuybrushAssignRoleRedAndBlueAndGreen"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1125,8 +1037,6 @@ public void test230GuybrushAssignRoleRedAndBlueAndGreen() throws Exception { */ @Test public void test240GuybrushAssignRoleExecutiveOne() throws Exception { - final String TEST_NAME = "test240GuybrushAssignRoleExecutiveOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1149,14 +1059,12 @@ public void test240GuybrushAssignRoleExecutiveOne() throws Exception { */ @Test public void test242GuybrushAssignRoleControllingOne() throws Exception { - final String TEST_NAME = "test242GuybrushAssignRoleControllingOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); + PrismObject userAfter = assignRolePolicyFailure(USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); // THEN assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); @@ -1167,8 +1075,6 @@ public void test242GuybrushAssignRoleControllingOne() throws Exception { */ @Test public void test244GuybrushAssignRoleExecutiveTwo() throws Exception { - final String TEST_NAME = "test244GuybrushAssignRoleExecutiveTwo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1192,14 +1098,12 @@ public void test244GuybrushAssignRoleExecutiveTwo() throws Exception { */ @Test public void test245GuybrushAssignRoleControllingTwo() throws Exception { - final String TEST_NAME = "test245GuybrushAssignRoleControllingTwo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CONTROLLING_2_OID, task, result); + PrismObject userAfter = assignRolePolicyFailure(USER_GUYBRUSH_OID, ROLE_CONTROLLING_2_OID, task, result); // THEN assertAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); @@ -1212,8 +1116,6 @@ public void test245GuybrushAssignRoleControllingTwo() throws Exception { */ @Test public void test246GuybrushUnassignRoleExecutiveOne() throws Exception { - final String TEST_NAME = "test246GuybrushUnassignRoleExecutiveOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1236,14 +1138,12 @@ public void test246GuybrushUnassignRoleExecutiveOne() throws Exception { */ @Test public void test247GuybrushAssignRoleControllingOne() throws Exception { - final String TEST_NAME = "test247GuybrushAssignRoleControllingOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); + PrismObject userAfter = assignRolePolicyFailure(USER_GUYBRUSH_OID, ROLE_CONTROLLING_1_OID, task, result); // THEN assertNotAssignedRole(userAfter, ROLE_EXECUTIVE_1_OID); @@ -1256,8 +1156,6 @@ public void test247GuybrushAssignRoleControllingOne() throws Exception { */ @Test public void test249GuybrushUnassignRoleExecutiveTwo() throws Exception { - final String TEST_NAME = "test249GuybrushUnassignRoleExecutiveTwo"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1283,8 +1181,6 @@ public void test249GuybrushUnassignRoleExecutiveTwo() throws Exception { */ @Test public void test250GuybrushAssignRoleControllingOne() throws Exception { - final String TEST_NAME = "test250GuybrushAssignRoleControllingOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1307,14 +1203,12 @@ public void test250GuybrushAssignRoleControllingOne() throws Exception { */ @Test public void test252GuybrushAssignRoleExecutiveOne() throws Exception { - final String TEST_NAME = "test252GuybrushAssignRoleExecutiveOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_EXECUTIVE_1_OID, task, result); + PrismObject userAfter = assignRolePolicyFailure(USER_GUYBRUSH_OID, ROLE_EXECUTIVE_1_OID, task, result); // THEN assertAssignedRole(userAfter, ROLE_CONTROLLING_1_OID); @@ -1325,8 +1219,6 @@ public void test252GuybrushAssignRoleExecutiveOne() throws Exception { */ @Test public void test259GuybrushUnassignRoleControllingOne() throws Exception { - final String TEST_NAME = "test259GuybrushUnassignRoleControllingOne"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1349,8 +1241,6 @@ public void test259GuybrushUnassignRoleControllingOne() throws Exception { @Test public void test800ApplyGlobalPolicyRulesExclusion() throws Exception { - final String TEST_NAME = "test800ApplyGlobalPolicyRulesExclusion"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1370,8 +1260,6 @@ public void test800ApplyGlobalPolicyRulesExclusion() throws Exception { @Test public void test810GuybrushAssignRoleCitizenSk() throws Exception { - final String TEST_NAME = "test810GuybrushAssignRoleCitizenSk"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1391,14 +1279,12 @@ public void test810GuybrushAssignRoleCitizenSk() throws Exception { @Test public void test812GuybrushAssignRoleCitizenUs() throws Exception { - final String TEST_NAME = "test812GuybrushAssignRoleCitizenUs"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN - PrismObject userAfter = assignRolePolicyFailure(TEST_NAME, USER_GUYBRUSH_OID, ROLE_CITIZEN_US_OID, task, result); + PrismObject userAfter = assignRolePolicyFailure(USER_GUYBRUSH_OID, ROLE_CITIZEN_US_OID, task, result); // THEN assertAssignedRole(userAfter, ROLE_CITIZEN_SK_OID); @@ -1409,8 +1295,6 @@ public void test812GuybrushAssignRoleCitizenUs() throws Exception { */ @Test public void test814GuybrushAssignRoleEmpty() throws Exception { - final String TEST_NAME = "test814GuybrushAssignRoleEmpty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1431,8 +1315,6 @@ public void test814GuybrushAssignRoleEmpty() throws Exception { @Test public void test818GuybrushUnassignRoleCitizenSk() throws Exception { - final String TEST_NAME = "test818GuybrushUnassignRoleCitizenSk"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1455,8 +1337,6 @@ public void test818GuybrushUnassignRoleCitizenSk() throws Exception { @Test public void test819GuybrushUnassignRoleEmpty() throws Exception { - final String TEST_NAME = "test818GuybrushUnassignRoleCitizenSk"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1480,8 +1360,6 @@ public void test819GuybrushUnassignRoleEmpty() throws Exception { */ @Test public void test820GuybrushAssignRoleCriminal() throws Exception { - final String TEST_NAME = "test820GuybrushAssignRoleCriminal"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1505,8 +1383,6 @@ public void test820GuybrushAssignRoleCriminal() throws Exception { */ @Test public void test822GuybrushAssignRoleMinister() throws Exception { - final String TEST_NAME = "test822GuybrushAssignRoleMinister"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1529,8 +1405,6 @@ public void test822GuybrushAssignRoleMinister() throws Exception { @Test public void test826GuybrushUnassignRoleCriminal() throws Exception { - final String TEST_NAME = "test826GuybrushUnassignRoleCriminal"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1551,8 +1425,6 @@ public void test826GuybrushUnassignRoleCriminal() throws Exception { @Test public void test829GuybrushUnassignRoleMinister() throws Exception { - final String TEST_NAME = "test829GuybrushUnassignRoleMinister"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1573,8 +1445,6 @@ public void test829GuybrushUnassignRoleMinister() throws Exception { @Test public void test900ApplyGlobalPolicyRulesSoDApproval() throws Exception { - final String TEST_NAME = "test900ApplyGlobalPolicyRulesSoDApproval"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1591,7 +1461,6 @@ public void test900ApplyGlobalPolicyRulesSoDApproval() throws Exception { assertEquals("Wrong number of global policy rules", NUMBER_OF_GLOBAL_POLICY_RULES + 2, globalPolicyRules.size()); } - /** * Minister and Criminal are mutually exclusive. There is not enforcement for * this in the roles. But now there is a global policy rule that drives this through @@ -1599,8 +1468,6 @@ public void test900ApplyGlobalPolicyRulesSoDApproval() throws Exception { */ @Test public void test920GuybrushAssignRoleCriminal() throws Exception { - final String TEST_NAME = "test920GuybrushAssignRoleCriminal"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1628,8 +1495,6 @@ public void test920GuybrushAssignRoleCriminal() throws Exception { */ @Test public void test922GuybrushPreviewAssignRoleMinister() throws Exception { - final String TEST_NAME = "test922GuybrushPreviewAssignRoleMinister"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1670,7 +1535,7 @@ public void test922GuybrushPreviewAssignRoleMinister() throws Exception { EvaluatedPolicyRuleTrigger sodTrigger = getSinglePolicyRuleTrigger(evaluatedSodPolicyRule, evaluatedSodPolicyRule.getTriggers()); display("Own trigger", sodTrigger); assertEvaluatedPolicyRuleTriggers(evaluatedSodPolicyRule, evaluatedSodPolicyRule.getAllTriggers(), 2); - EvaluatedPolicyRuleTrigger situationTrigger = getEvaluatedPolicyRuleTrigger(evaluatedSodPolicyRule, evaluatedSodPolicyRule.getAllTriggers(), PolicyConstraintKindType.SITUATION); + EvaluatedPolicyRuleTrigger situationTrigger = getEvaluatedPolicyRuleTrigger(evaluatedSodPolicyRule.getAllTriggers(), PolicyConstraintKindType.SITUATION); display("Situation trigger", situationTrigger); PolicyActionsType sodActions = evaluatedSodPolicyRule.getActions(); display("Actions", sodActions); @@ -1679,13 +1544,13 @@ public void test922GuybrushPreviewAssignRoleMinister() throws Exception { private void assertPolicyActionApproval(EvaluatedPolicyRule evaluatedPolicyRule) { PolicyActionsType actions = evaluatedPolicyRule.getActions(); - assertNotNull("No policy actions in "+evaluatedPolicyRule, actions); - assertFalse("No approval action in "+evaluatedPolicyRule, actions.getApproval().isEmpty()); + assertNotNull("No policy actions in " + evaluatedPolicyRule, actions); + assertFalse("No approval action in " + evaluatedPolicyRule, actions.getApproval().isEmpty()); } private void assertEvaluatedPolicyRuleTriggers(EvaluatedPolicyRule evaluatedPolicyRule, Collection> triggers, int expectedNumberOfTriggers) { - assertEquals("Wrong number of triggers in evaluated policy rule "+evaluatedPolicyRule.getName(), expectedNumberOfTriggers, triggers.size()); + assertEquals("Wrong number of triggers in evaluated policy rule " + evaluatedPolicyRule.getName(), expectedNumberOfTriggers, triggers.size()); } private EvaluatedPolicyRuleTrigger getSinglePolicyRuleTrigger(EvaluatedPolicyRule evaluatedPolicyRule, Collection> triggers) { @@ -1693,20 +1558,17 @@ private EvaluatedPolicyRuleTrigger getSinglePolicyRuleTrigger(EvaluatedPolicy return triggers.iterator().next(); } - private EvaluatedPolicyRuleTrigger getEvaluatedPolicyRuleTrigger(EvaluatedPolicyRule evaluatedPolicyRule, + private EvaluatedPolicyRuleTrigger getEvaluatedPolicyRuleTrigger( Collection> triggers, PolicyConstraintKindType expectedConstraintType) { return triggers.stream().filter(trigger -> expectedConstraintType.equals(trigger.getConstraintKind())).findFirst().get(); } - private EvaluatedPolicyRule getEvaluatedPolicyRule(Collection evaluatedPolicyRules, String ruleName) { return evaluatedPolicyRules.stream().filter(rule -> ruleName.equals(rule.getName())).findFirst().get(); } @Test public void test929GuybrushUnassignRoleCriminal() throws Exception { - final String TEST_NAME = "test929GuybrushUnassignRoleCriminal"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1728,14 +1590,12 @@ public void test929GuybrushUnassignRoleCriminal() throws Exception { /** * This does not work because of current optimizations regarding non-default relations: * "2018-02-19 17:02:15,977 [main] DEBUG (c.e.m.model.impl.lens.AssignmentEvaluator): Skipping processing of assignment target 9577bd6c-dd5d-48e5-bbb1-554bba5db9be because - * relation {http://midpoint.evolveum.com/xml/ns/public/common/org-3}approver is configured for recompute skip (mode=ZERO)" - * + * relation {http://midpoint.evolveum.com/xml/ns/public/common/org-3}approver is configured for recompute skip (mode=ZERO)" + *

* i.e. it works only when evaluateAllAssignmentRelationsOnRecompute option is set */ @Test(enabled = false) public void test950JackSelfExclusion() throws Exception { - final String TEST_NAME = "test950JackSelfExclusion"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1765,8 +1625,6 @@ public void test950JackSelfExclusion() throws Exception { @Test public void test952JackSelfExclusionManagerMember() throws Exception { - final String TEST_NAME = "test952JackSelfExclusionManagerMember"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1795,8 +1653,6 @@ public void test952JackSelfExclusionManagerMember() throws Exception { // MID-5207 @Test public void test960JimGoldByMapping() throws Exception { - final String TEST_NAME = "test960JimGoldByMapping"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1805,7 +1661,7 @@ public void test960JimGoldByMapping() throws Exception { UserType jim = new UserType(prismContext) .name("jim") .beginAssignment() - .targetRef(ROLE_PRIZE_SILVER_OID, RoleType.COMPLEX_TYPE) + .targetRef(ROLE_PRIZE_SILVER_OID, RoleType.COMPLEX_TYPE) .end(); addObject(jim.asPrismObject()); @@ -1827,7 +1683,11 @@ public void test960JimGoldByMapping() throws Exception { assertNotAssignedRole(userAfter, ROLE_PRIZE_BRONZE_OID); } - private PrismObject assignRolePolicyFailure(String TEST_NAME, String userOid, String roleOid, Task task, OperationResult result) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, SecurityViolationException { + private PrismObject assignRolePolicyFailure( + String userOid, String roleOid, Task task, OperationResult result) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + SecurityViolationException { try { // WHEN @@ -1849,15 +1709,4 @@ private PrismObject assignRolePolicyFailure(String TEST_NAME, String u assertNotAssignedRole(userAfter, roleOid); return userAfter; } - - private void assertPolicySituation(PrismObject user, String targetOid, String... expectedPolicySituation) { - for (AssignmentType assignment: user.asObjectable().getAssignment()) { - ObjectReferenceType targetRef = assignment.getTargetRef(); - if (targetRef != null && targetOid.equals(targetRef.getOid())) { - PrismAsserts.assertSets("Wrong policy situation for target "+targetOid+" in "+user, assignment.getPolicySituation(), expectedPolicySituation); - } - } - } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java index db98a3d791c..585cf3d7840 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityAdvanced.java @@ -159,7 +159,6 @@ protected int getNumberOfRoles() { */ @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -187,7 +186,6 @@ public void test000Sanity() throws Exception { */ @Test public void test080AutzJackEndUserPassword() throws Exception { - final String TEST_NAME = "test080AutzJackEndUserPassword"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -230,7 +228,6 @@ public void test080AutzJackEndUserPassword() throws Exception { @Test public void test100AutzJackPersonaManagement() throws Exception { - final String TEST_NAME = "test100AutzJackPersonaManagement"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PERSONA_MANAGEMENT_OID); @@ -256,7 +253,6 @@ public void test100AutzJackPersonaManagement() throws Exception { @Test public void test102AutzLechuckPersonaManagement() throws Exception { - final String TEST_NAME = "test102AutzLechuckPersonaManagement"; // GIVEN cleanupAutzTest(USER_LECHUCK_OID, 1); assignRole(USER_LECHUCK_OID, ROLE_PERSONA_MANAGEMENT_OID); @@ -286,7 +282,6 @@ public void test102AutzLechuckPersonaManagement() throws Exception { */ @Test public void test110AutzJackPersonaAdmin() throws Exception { - final String TEST_NAME = "test110AutzJackAddPersonaAdmin"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PERSONA_MANAGEMENT_OID); @@ -342,7 +337,6 @@ public void test110AutzJackPersonaAdmin() throws Exception { @Test public void test120AutzJackDelagator() throws Exception { - final String TEST_NAME = "test120AutzJackDelagator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_DELEGATOR_OID); @@ -449,7 +443,6 @@ public void test120AutzJackDelagator() throws Exception { */ @Test public void test122AutzJackDelagatorValidity() throws Exception { - final String TEST_NAME = "test122AutzJackDelagatorValidity"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_DELEGATOR_OID); @@ -595,7 +588,6 @@ public void test122AutzJackDelagatorValidity() throws Exception { */ @Test public void test124AutzJackDelagatorPlusValidity() throws Exception { - final String TEST_NAME = "test124AutzJackDelagatorPlusValidity"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_DELEGATOR_PLUS_OID); @@ -750,7 +742,6 @@ public void test124AutzJackDelagatorPlusValidity() throws Exception { @Test public void test150AutzJackApproverUnassignRoles() throws Exception { - final String TEST_NAME = "test150AutzJackApproverUnassignRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID); @@ -794,7 +785,6 @@ public void test150AutzJackApproverUnassignRoles() throws Exception { @Test public void test151AutzJackApproverUnassignRolesAndRead() throws Exception { - final String TEST_NAME = "test151AutzJackApproverUnassignRolesAndRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_APPROVER_UNASSIGN_ROLES_OID); @@ -836,7 +826,6 @@ public void test151AutzJackApproverUnassignRolesAndRead() throws Exception { */ @Test public void test154AutzJackApproverRead() throws Exception { - final String TEST_NAME = "test154AutzJackApproverRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_BASIC_ITEMS_OID); @@ -901,7 +890,6 @@ public void test154AutzJackApproverRead() throws Exception { */ @Test public void test155AutzJackApproverSelf() throws Exception { - final String TEST_NAME = "test155AutzJackApproverSelf"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_SELF_OID); @@ -958,7 +946,6 @@ public void test155AutzJackApproverSelf() throws Exception { @Test public void test157AutzJackReadRoleMembers() throws Exception { - final String TEST_NAME = "test157AutzJackReadRoleMembers"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_OID); @@ -1010,7 +997,6 @@ public void test157AutzJackReadRoleMembers() throws Exception { @Test public void test158AutzJackReadRoleMembersWrong() throws Exception { - final String TEST_NAME = "test158AutzJackReadRoleMembersWrong"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_WRONG_OID); @@ -1062,7 +1048,6 @@ public void test158AutzJackReadRoleMembersWrong() throws Exception { @Test public void test159AutzJackReadRoleMembersNone() throws Exception { - final String TEST_NAME = "test159AutzJackReadRoleMembersNone"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_ROLE_MEMBERS_NONE_OID); @@ -1164,7 +1149,6 @@ private void assert15xCommon() throws Exception { */ @Test public void test200AutzJackModifyOrgunit() throws Exception { - final String TEST_NAME = "test200AutzJackModifyOrgunit"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_SELF_MODIFY_ORGUNIT_OID); @@ -1224,7 +1208,6 @@ public void test200AutzJackModifyOrgunit() throws Exception { */ @Test public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { - final String TEST_NAME = "test202AutzJackModifyOrgunitAndAssignRole"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_READ_SELF_MODIFY_ORGUNIT_OID); @@ -1298,7 +1281,6 @@ public void test202AutzJackModifyOrgunitAndAssignRole() throws Exception { */ @Test public void test220AutzJackRoleExpressionNoConstCenter() throws Exception { - final String TEST_NAME = "test220AutzJackRoleExpressionNoConstCenter"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EXPRESSION_READ_ROLES_OID); @@ -1337,7 +1319,6 @@ public void test220AutzJackRoleExpressionNoConstCenter() throws Exception { */ @Test public void test222AutzJackRoleExpressionConstCenterBusiness() throws Exception { - final String TEST_NAME = "test222AutzJackRoleExpressionConstCenterBusiness"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EXPRESSION_READ_ROLES_OID); @@ -1379,7 +1360,6 @@ public void test222AutzJackRoleExpressionConstCenterBusiness() throws Exception */ @Test public void test230AttorneyCaribbeanUnlimited() throws Exception { - final String TEST_NAME = "test230AttorneyCaribbeanUnlimited"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_CARIBBEAN_UNLIMITED_OID); @@ -1452,7 +1432,6 @@ public void test230AttorneyCaribbeanUnlimited() throws Exception { */ @Test public void test232ManagerAttorneyNoOrg() throws Exception { - final String TEST_NAME = "test232ManagerAttorneyNoOrg"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_MANAGER_WORKITEMS_OID); @@ -1501,7 +1480,6 @@ public void test232ManagerAttorneyNoOrg() throws Exception { */ @Test public void test234ManagerAttorneyRum() throws Exception { - final String TEST_NAME = "test234ManagerAttorneyRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_MANAGER_WORKITEMS_OID); @@ -1567,7 +1545,6 @@ public void test234ManagerAttorneyRum() throws Exception { */ @Test public void test235ManagerAttorneyRumRogersEntitled() throws Exception { - final String TEST_NAME = "test234ManagerAttorneyRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_MANAGER_WORKITEMS_OID); @@ -1635,7 +1612,6 @@ public void test235ManagerAttorneyRumRogersEntitled() throws Exception { */ @Test public void test236ManagerAttorneyCaribbeanRum() throws Exception { - final String TEST_NAME = "test236ManagerAttorneyCaribbeanRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ATTORNEY_CARIBBEAN_UNLIMITED_OID); @@ -1716,7 +1692,6 @@ public void test236ManagerAttorneyCaribbeanRum() throws Exception { */ @Test public void test250AssignRequestableSelfOtherApporver() throws Exception { - final String TEST_NAME = "test250AssignRequestableSelfOtherApporver"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_SELF_REQUESTABLE_ANY_APPROVER_OID); @@ -1809,7 +1784,6 @@ public void test250AssignRequestableSelfOtherApporver() throws Exception { */ @Test public void test252AssignRequestableSelfOtherApporverEmptyDelta() throws Exception { - final String TEST_NAME = "test252AssignRequestableSelfOtherApporverEmptyDelta"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_SELF_REQUESTABLE_ANY_APPROVER_OID); @@ -1880,7 +1854,6 @@ public void test252AssignRequestableSelfOtherApporverEmptyDelta() throws Excepti @Test public void test254AssignUnassignRequestableSelf() throws Exception { - final String TEST_NAME = "test254AssignUnassignRequestableSelf"; // GIVENds cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_UNASSIGN_SELF_REQUESTABLE_OID); @@ -1916,7 +1889,6 @@ public void test254AssignUnassignRequestableSelf() throws Exception { @Test public void test256AssignUnassignRequestableSelfEmptyDelta() throws Exception { - final String TEST_NAME = "test256AssignUnassignRequestableSelfEmptyDelta"; // GIVENds cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_UNASSIGN_SELF_REQUESTABLE_OID); @@ -1952,7 +1924,6 @@ public void test256AssignUnassignRequestableSelfEmptyDelta() throws Exception { @Test public void test260AutzJackLimitedRoleAdministrator() throws Exception { - final String TEST_NAME = "test260AutzJackLimitedRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2089,7 +2060,6 @@ public void test260AutzJackLimitedRoleAdministrator() throws Exception { */ @Test public void test262AutzJackLimitedRoleAdministratorAndAssignApplicationRoles() throws Exception { - final String TEST_NAME = "test260AutzJackLimitedRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2215,7 +2185,6 @@ public void test262AutzJackLimitedRoleAdministratorAndAssignApplicationRoles() t */ @Test public void test264AutzJackLimitedReadRoleAdministrator() throws Exception { - final String TEST_NAME = "test264AutzJackLimitedReadRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_READ_ROLE_ADMINISTRATOR_OID); @@ -2316,7 +2285,6 @@ public void test264AutzJackLimitedReadRoleAdministrator() throws Exception { */ @Test public void test266AutzJackRoleAdministrator() throws Exception { - final String TEST_NAME = "test266AutzJackRoleAdministrator"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ROLE_ADMINISTRATOR_OID); @@ -2373,7 +2341,6 @@ public void test266AutzJackRoleAdministrator() throws Exception { @Test public void test270AutzJackModifyPolicyException() throws Exception { - final String TEST_NAME = "test270AutzJackModifyPolicyException"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_MODIFY_POLICY_EXCEPTION_OID); @@ -2430,7 +2397,6 @@ public void test270AutzJackModifyPolicyException() throws Exception { @Test public void test272AutzJackModifyPolicyExceptionFirstRule() throws Exception { - final String TEST_NAME = "test272AutzJackModifyPolicyExceptionFirstRule"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_MODIFY_POLICY_EXCEPTION_OID); @@ -2530,7 +2496,6 @@ public void test274AutzJackModifyPolicyExceptionSituation() throws Exception { */ @Test public void test280AutzJackModifyPolicyExceptionAndAssignOrg() throws Exception { - final String TEST_NAME = "test280AutzJackModifyPolicyExceptionAndAssignOrg"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2566,7 +2531,6 @@ public void test280AutzJackModifyPolicyExceptionAndAssignOrg() throws Exception */ @Test public void test282AutzJackModifyPolicyExceptionAndAssignOrgDeny() throws Exception { - final String TEST_NAME = "test282AutzJackModifyPolicyExceptionAndAssignOrgDeny"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_LIMITED_ROLE_ADMINISTRATOR_OID); @@ -2599,7 +2563,6 @@ public void test282AutzJackModifyPolicyExceptionAndAssignOrgDeny() throws Except */ @Test public void test283AutzJackModifyPolicyAssignOrg() throws Exception { - final String TEST_NAME = "test283AutzJackModifyPolicyAssignOrg"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_ORG_OID); @@ -2642,7 +2605,6 @@ protected void modifyRoleAddExclusionAndAssignOrg( @Test public void test300AutzJackExceptAssignment() throws Exception { - final String TEST_NAME = "test300AutzJackExceptAssignment"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_EXCEPT_ASSIGNMENT_OID); @@ -2705,7 +2667,6 @@ public void test300AutzJackExceptAssignment() throws Exception { @Test public void test302AutzJackExceptAdministrativeStatus() throws Exception { - final String TEST_NAME = "test302AutzJackExceptAdministrativeStatus"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_EXCEPT_ADMINISTRATIVE_STATUS_OID); @@ -2773,7 +2734,6 @@ public void test302AutzJackExceptAdministrativeStatus() throws Exception { */ @Test public void test304AutzJackPropExceptAssignmentReadSomeModifySomeUser() throws Exception { - final String TEST_NAME = "test304AutzJackPropExceptAssignmentReadSomeModifySomeUser"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_READ_SOME_MODIFY_SOME_USER_OID); @@ -2830,7 +2790,6 @@ public void test304AutzJackPropExceptAssignmentReadSomeModifySomeUser() throws E */ @Test public void test306AutzJackPropExceptAssignmentExceptAdministrativeStatus() throws Exception { - final String TEST_NAME = "test306AutzJackPropExceptAssignmentExceptAdministrativeStatus"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_EXCEPT_ADMINISTRATIVE_STATUS_OID); @@ -2887,7 +2846,6 @@ public void test306AutzJackPropExceptAssignmentExceptAdministrativeStatus() thro */ @Test public void test308AutzJackPropExceptAssignmentAssignApplicationRoles() throws Exception { - final String TEST_NAME = "test308AutzJackPropExceptAssignmentAssignApplicationRoles"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_ASSIGN_APPLICATION_ROLES_OID); @@ -2981,7 +2939,6 @@ public void test308AutzJackPropExceptAssignmentAssignApplicationRoles() throws E */ @Test public void test310AutzJackPropSubtypeDenyEscapingZoneOfControl() throws Exception { - final String TEST_NAME = "test310AutzJackPropSubtypeDenyEscapingZoneOfControl"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_SUBTYPE_OID); @@ -3016,7 +2973,6 @@ public void test310AutzJackPropSubtypeDenyEscapingZoneOfControl() throws Excepti */ @Test public void test312AutzJackPropSubtypeAllowEscapingZoneOfControl() throws Exception { - final String TEST_NAME = "test312AutzJackPropSubtypeAllowEscapingZoneOfControl"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_PROP_SUBTYPE_ESCAPE_OID); @@ -3102,7 +3058,6 @@ public void test320AutzJackGuybrushValutDweller() throws Exception { */ @Test public void test330AutzJackEndUserWithPrivacy() throws Exception { - final String TEST_NAME = "test330AutzJackEndUserWithPrivacy"; // GIVEN cleanupAutzTest(USER_JACK_OID); assertNoDummyAccount(RESOURCE_DUMMY_VAULT_NAME, USER_GUYBRUSH_USERNAME); @@ -3148,7 +3103,6 @@ public void test330AutzJackEndUserWithPrivacy() throws Exception { */ @Test public void test340AutzJackSuperUserAndExecRead() throws Exception { - final String TEST_NAME = "test340AutzJackSuperUserAndExecRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3181,7 +3135,6 @@ public void test340AutzJackSuperUserAndExecRead() throws Exception { */ @Test public void test350AutzJackResourceRead() throws Exception { - final String TEST_NAME = "test350AutzJackResourceRead"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -3207,7 +3160,6 @@ public void test350AutzJackResourceRead() throws Exception { */ @Test public void test360AutzAdminResourceRead() throws Exception { - final String TEST_NAME = "test350AutzAdminResourceRead"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); @@ -3286,10 +3238,13 @@ private AssignmentType assertExclusion(PrismObject roleExclusion, Stri } @Override - protected void cleanupAutzTest(String userOid, int expectedAssignments) throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, CommunicationException, ConfigurationException, ObjectAlreadyExistsException, PolicyViolationException, SecurityViolationException, IOException { + protected void cleanupAutzTest(String userOid, int expectedAssignments) + throws ObjectNotFoundException, SchemaException, ExpressionEvaluationException, + CommunicationException, ConfigurationException, ObjectAlreadyExistsException, + PolicyViolationException, SecurityViolationException, IOException { super.cleanupAutzTest(userOid, expectedAssignments); - Task task = taskManager.createTaskInstance(TestSecurityAdvanced.class.getName() + ".cleanupAutzTest"); + Task task = getTestTask(); OperationResult result = task.getResult(); assignRole(userRumRogersOid, ROLE_ORDINARY_OID, task, result); @@ -3299,14 +3254,16 @@ protected void cleanupAutzTest(String userOid, int expectedAssignments) throws O } - private void assertDeputySearchDelegatorRef(String delegatorOid, String... expectedDeputyOids) throws Exception { + private void assertDeputySearchDelegatorRef(String delegatorOid, String... expectedDeputyOids) + throws Exception { PrismReferenceValue rval = itemFactory().createReferenceValue(delegatorOid, UserType.COMPLEX_TYPE); rval.setRelation(SchemaConstants.ORG_DEPUTY); ObjectQuery query = queryFor(UserType.class).item(UserType.F_DELEGATED_REF).ref(rval).build(); assertSearch(UserType.class, query, expectedDeputyOids); } - private void assertDeputySearchAssignmentTarget(String delegatorOid, String... expectedDeputyOids) throws Exception { + private void assertDeputySearchAssignmentTarget( + String delegatorOid, String... expectedDeputyOids) throws Exception { PrismReferenceValue rval = itemFactory().createReferenceValue(delegatorOid, UserType.COMPLEX_TYPE); rval.setRelation(SchemaConstants.ORG_DEPUTY); ObjectQuery query = queryFor(UserType.class) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java index 8f38fc3e0b9..8b148cdd5bf 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java @@ -1339,7 +1339,6 @@ public void test241AutzJackManagerFullControlMemberMinistryOfRum() throws Except */ @Test public void test242AutzJackManagerFullControlManagerMinistryOfRum() throws Exception { - final String TEST_NAME = "test242AutzJackManagerFullControlManagerMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1357,7 +1356,7 @@ public void test242AutzJackManagerFullControlManagerMinistryOfRum() throws Excep // WHEN when(); - assertJack24xManager(TEST_NAME, true); + assertJack24xManager(true); assertGlobalStateUntouched(); } @@ -1367,7 +1366,6 @@ public void test242AutzJackManagerFullControlManagerMinistryOfRum() throws Excep */ @Test public void test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense() throws Exception { - final String TEST_NAME = "test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1388,7 +1386,7 @@ public void test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense() th // WHEN when(); - assertJack24xManagerDefense(TEST_NAME, true); + assertJack24xManagerDefense(true); assertGlobalStateUntouched(); } @@ -1423,7 +1421,6 @@ public void test245AutzJackManagerUserAdminMemberMinistryOfRum() throws Exceptio */ @Test public void test246AutzJackManagerUserAdminManagerMinistryOfRum() throws Exception { - final String TEST_NAME = "test246AutzJackManagerUserAdminManagerMinistryOfRum"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1441,7 +1438,7 @@ public void test246AutzJackManagerUserAdminManagerMinistryOfRum() throws Excepti // WHEN when(); - assertJack24xManager(TEST_NAME, false); + assertJack24xManager(false); assertGlobalStateUntouched(); } @@ -1451,7 +1448,6 @@ public void test246AutzJackManagerUserAdminManagerMinistryOfRum() throws Excepti */ @Test public void test247AutzJackManagerUserAdminManagerMinistryOfRumAndDefense() throws Exception { - final String TEST_NAME = "test243AutzJackManagerFullControlManagerMinistryOfRumAndDefense"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -1470,7 +1466,7 @@ public void test247AutzJackManagerUserAdminManagerMinistryOfRumAndDefense() thro // WHEN when(); - assertJack24xManagerDefense(TEST_NAME, false); + assertJack24xManagerDefense(false); assertGlobalStateUntouched(); } @@ -1504,7 +1500,7 @@ private void assertJack24xMember(String accountOid) throws Exception { new QName(RESOURCE_DUMMY_NAMESPACE, "AccountObjectClass"), prismContext)), 0); } - private void assertJack24xManager(final String TEST_NAME, boolean fullControl) throws Exception { + private void assertJack24xManager(boolean fullControl) throws Exception { assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); @@ -1530,7 +1526,7 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t assertAddDenyRaw(USER_MANCOMB_FILE); assertAddAllow(USER_MANCOMB_FILE); // MID-3874 - Task task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); + Task task = createPlainTask(); OperationResult result = task.getResult(); try { addObject(ORG_CHEATERS_FILE, task, result); // MID-3874 @@ -1570,7 +1566,7 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t // MID-2822 - task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); + task = createPlainTask(); result = task.getResult(); ObjectQuery query = prismContext.queryFactory().createQuery( @@ -1599,7 +1595,7 @@ private void assertJack24xManager(final String TEST_NAME, boolean fullControl) t assertVisibleUsers(4); } - private void assertJack24xManagerDefense(String TEST_NAME, boolean fullControl) throws Exception { + private void assertJack24xManagerDefense(boolean fullControl) throws Exception { assertGetAllow(UserType.class, USER_JACK_OID); assertGetDeny(UserType.class, USER_JACK_OID, SelectorOptions.createCollection(GetOperationOptions.createRaw())); assertGetDeny(UserType.class, USER_GUYBRUSH_OID); @@ -1654,7 +1650,7 @@ private void assertJack24xManagerDefense(String TEST_NAME, boolean fullControl) // MID-2822 - Task task = taskManager.createTaskInstance(TestSecurityBasic.class.getName() + "." + TEST_NAME); + Task task = createPlainTask(); OperationResult result = task.getResult(); ObjectQuery query = prismContext.queryFactory().createQuery( @@ -3003,7 +2999,7 @@ public void test295AutzJackAssignOrgRelation() throws Exception { .assertNotNull() .getFilter(); - Task task = taskManager.createTaskInstance(); + Task task = createPlainTask(); SearchResultList> assignableRolesJack = modelService.searchObjects(AbstractRoleType.class, prismContext.queryFactory().createQuery(jackAssignableRoleFilter), null, task, task.getResult()); display("Assignable roles", assignableRolesJack); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java index 0f03b6409da..847f36f7979 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMedium.java @@ -21,14 +21,12 @@ /** * @author semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestSecurityMedium extends AbstractSecurityTest { protected static final File USER_EMPLOYEE_FRED_FILE = new File(TEST_DIR, "user-employee-fred.xml"); - protected static final String USER_EMPLOYEE_FRED_OID = "4e63d9a2-d575-11e9-9c19-cb0e0207a10e"; protected static final File ROLE_EMPLOYEE_MANAGER_FILE = new File(TEST_DIR, "role-employee-manager.xml"); protected static final String ROLE_EMPLOYEE_MANAGER_OID = "5549cb8e-d573-11e9-a61e-7f2eff22715a"; @@ -53,7 +51,6 @@ protected int getNumberOfRoles() { */ @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -77,7 +74,6 @@ public void test000Sanity() throws Exception { */ @Test public void test100AutzEmployeeManager() throws Exception { - final String TEST_NAME = "test100AutzEmployeeManager"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EMPLOYEE_MANAGER_OID); @@ -107,7 +103,6 @@ public void test100AutzEmployeeManager() throws Exception { */ @Test public void test102AutzEmployeeManagerAddEmployee() throws Exception { - final String TEST_NAME = "test102AutzEmployeeManagerAddEmployee"; // GIVEN cleanupAutzTest(USER_JACK_OID); assignRole(USER_JACK_OID, ROLE_EMPLOYEE_MANAGER_OID); @@ -126,6 +121,4 @@ public void test102AutzEmployeeManagerAddEmployee() throws Exception { assertDeleteDeny(); assertGlobalStateUntouched(); } - - } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java index 1449864b2ee..203c5911a22 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityMultitenant.java @@ -211,7 +211,6 @@ protected int getNumberOfRoles() { */ @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; // GIVEN cleanupAutzTest(USER_JACK_OID); @@ -239,7 +238,6 @@ public void test000Sanity() throws Exception { */ @Test public void test010ImportOrgstruct() throws Exception { - final String TEST_NAME = "test010ImportOrgstruct"; // GIVEN Task task = getTestTask(); @@ -375,7 +373,6 @@ public void test010ImportOrgstruct() throws Exception { */ @Test public void test100AutzLetoRead() throws Exception { - final String TEST_NAME = "test100AutzLetoRead"; // GIVEN cleanupAutzTest(null); @@ -416,7 +413,6 @@ public void test100AutzLetoRead() throws Exception { */ @Test public void test102AutzLetoAdd() throws Exception { - final String TEST_NAME = "test102AutzLetoAdd"; // GIVEN cleanupAutzTest(null); @@ -460,7 +456,6 @@ public void test102AutzLetoAdd() throws Exception { */ @Test public void test104AutzLetoModify() throws Exception { - final String TEST_NAME = "test104AutzLetoModify"; // GIVEN cleanupAutzTest(null); @@ -491,7 +486,6 @@ public void test104AutzLetoModify() throws Exception { */ @Test public void test106AutzLetoAddResourceTask() throws Exception { - final String TEST_NAME = "test106AutzLetoAddResourceTask"; // GIVEN cleanupAutzTest(null); @@ -524,7 +518,7 @@ private void assertAddDummyResourceAllow(File file) throws SchemaException, IOEx assertAddAllow(resource, null); } - private void assertAddDummyResourceDeny(File file) throws SchemaException, IOException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { + private void assertAddDummyResourceDeny(File file) throws SchemaException, IOException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException { PrismObject resource = PrismTestUtil.parseObject(file); resource.asObjectable() .connectorRef(dummyConnector.getOid(), ConnectorType.COMPLEX_TYPE); @@ -536,7 +530,6 @@ private void assertAddDummyResourceDeny(File file) throws SchemaException, IOExc */ @Test public void test109AutzLetoDelete() throws Exception { - final String TEST_NAME = "test109AutzLetoDelete"; // GIVEN cleanupAutzTest(null); @@ -565,7 +558,6 @@ public void test109AutzLetoDelete() throws Exception { */ @Test public void test110AutzLetoAddOrgs() throws Exception { - final String TEST_NAME = "test110AutzLetoAddOrgs"; // GIVEN cleanupAutzTest(null); @@ -619,7 +611,6 @@ public void test110AutzLetoAddOrgs() throws Exception { */ @Test public void test112AutzLetoProtectTenant() throws Exception { - final String TEST_NAME = "test112AutzLetoProtectTenant"; // GIVEN cleanupAutzTest(null); @@ -688,7 +679,6 @@ public void test112AutzLetoProtectTenant() throws Exception { */ @Test public void test114AutzLetoKeepWithinTenant() throws Exception { - final String TEST_NAME = "test114AutzLetoKeepWithinTenant"; // GIVEN cleanupAutzTest(null); @@ -750,7 +740,6 @@ public void test114AutzLetoKeepWithinTenant() throws Exception { */ @Test public void test116AutzLetoProtectTenantAdminRole() throws Exception { - final String TEST_NAME = "test114AutzLetoKeepWithinTenant"; // GIVEN cleanupAutzTest(null); @@ -807,7 +796,6 @@ public void test116AutzLetoProtectTenantAdminRole() throws Exception { */ @Test public void test118AutzLetoBusinessRoles() throws Exception { - final String TEST_NAME = "test118AutzLetoBusinessRoles"; // GIVEN cleanupAutzTest(null); @@ -846,7 +834,6 @@ public void test118AutzLetoBusinessRoles() throws Exception { */ @Test public void test120AutzPaulEndUser() throws Exception { - final String TEST_NAME = "test120AutzPaulEndUser"; // GIVEN cleanupAutzTest(null); @@ -881,7 +868,6 @@ public void test120AutzPaulEndUser() throws Exception { @Test public void test122AutzDuncanRoleManager() throws Exception { - final String TEST_NAME = "test122AutzDuncanRoleManager"; // GIVEN cleanupAutzTest(null); @@ -930,7 +916,6 @@ public void test122AutzDuncanRoleManager() throws Exception { */ @Test public void test130AutzEdricRead() throws Exception { - final String TEST_NAME = "test120AutzEdricRead"; // GIVEN cleanupAutzTest(null); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java index 93c14b2ce37..babb347fcd9 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityPrincipal.java @@ -20,13 +20,11 @@ import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.security.api.MidPointPrincipal; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationPhaseType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -39,7 +37,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010GetUserAdministrator() throws Exception { - final String TEST_NAME = "test010GetUserAdministrator"; resetAuthentication(); // WHEN @@ -56,7 +53,6 @@ public void test010GetUserAdministrator() throws Exception { @Test public void test050GetUserJack() throws Exception { - final String TEST_NAME = "test050GetUserJack"; resetAuthentication(); // WHEN @@ -75,7 +71,6 @@ public void test050GetUserJack() throws Exception { @Test public void test051GetUserBarbossa() throws Exception { - final String TEST_NAME = "test051GetUserBarbossa"; resetAuthentication(); // WHEN @@ -97,7 +92,6 @@ public void test051GetUserBarbossa() throws Exception { @Test public void test052GetUserGuybrush() throws Exception { - final String TEST_NAME = "test052GetUserGuybrush"; resetAuthentication(); // WHEN @@ -118,7 +112,6 @@ public void test052GetUserGuybrush() throws Exception { @Test public void test060GuybrushConditionalRoleFalse() throws Exception { - final String TEST_NAME = "test060GuybrushConditionalRoleFalse"; login(USER_ADMINISTRATOR_USERNAME); assignRole(USER_GUYBRUSH_OID, ROLE_CONDITIONAL_OID); @@ -145,7 +138,6 @@ public void test060GuybrushConditionalRoleFalse() throws Exception { @Test public void test061GuybrushConditionalRoleTrue() throws Exception { - final String TEST_NAME = "test061GuybrushConditionalRoleTrue"; login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -176,7 +168,6 @@ public void test061GuybrushConditionalRoleTrue() throws Exception { @Test public void test062GuybrushConditionalRoleUnassign() throws Exception { - final String TEST_NAME = "test062GuybrushConditionalRoleUnassign"; login(USER_ADMINISTRATOR_USERNAME); unassignRole(USER_GUYBRUSH_OID, ROLE_CONDITIONAL_OID); @@ -201,7 +192,6 @@ public void test062GuybrushConditionalRoleUnassign() throws Exception { @Test public void test100JackRolePirate() throws Exception { - final String TEST_NAME = "test100JackRolePirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -234,7 +224,6 @@ public void test100JackRolePirate() throws Exception { @Test public void test109JackUnassignRolePirate() throws Exception { - final String TEST_NAME = "test109JackUnassignRolePirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -264,7 +253,6 @@ public void test109JackUnassignRolePirate() throws Exception { @Test public void test110GuybrushRoleNicePirate() throws Exception { - final String TEST_NAME = "test110GuybrushRoleNicePirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -288,7 +276,6 @@ public void test110GuybrushRoleNicePirate() throws Exception { @Test public void test111GuybrushRoleCaptain() throws Exception { - final String TEST_NAME = "test111GuybrushRoleCaptain"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -312,7 +299,6 @@ public void test111GuybrushRoleCaptain() throws Exception { @Test public void test119GuybrushUnassignRoles() throws Exception { - final String TEST_NAME = "test119GuybrushUnassignRoles"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); Task task = getTestTask(); @@ -339,7 +325,6 @@ public void test119GuybrushUnassignRoles() throws Exception { */ @Test public void test120JackRoleIndirectPirate() throws Exception { - final String TEST_NAME = "test120JackRoleIndirectPirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); @@ -371,7 +356,6 @@ public void test120JackRoleIndirectPirate() throws Exception { */ @Test public void test122JackOrgIndirectPirate() throws Exception { - final String TEST_NAME = "test122JackOrgIndirectPirate"; // GIVEN login(USER_ADMINISTRATOR_USERNAME); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java index 7c09d0feabb..f3d33bd5f8c 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java @@ -53,8 +53,6 @@ import com.evolveum.midpoint.schema.processor.ResourceSchema; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; -import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; -import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; @@ -69,10 +67,9 @@ /** * @author semancik - * */ @SuppressWarnings("SpellCheckingInspection") -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestImportRecon extends AbstractInitializedModelIntegrationTest { @@ -206,11 +203,11 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Create an account that midPoint does not know about yet getDummyResourceController().addAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, "Scabb Island"); getDummyResource().getAccountByUsername(USER_RAPP_USERNAME) - .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); + .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); dummyResourceCtlLime.addAccount(USER_RAPP_USERNAME, USER_RAPP_FULLNAME, "Scabb Island"); dummyResourceLime.getAccountByUsername(USER_RAPP_USERNAME) - .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); + .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The Elaine"); dummyResourceCtlLime.addAccount(ACCOUNT_RUM_NAME, "Rum Rogers"); dummyResourceCtlLime.addAccount(ACCOUNT_MURRAY_NAME, "Murray"); @@ -391,15 +388,15 @@ public void test150ImportFromResourceDummy() throws Exception { assertTask(task, "task after") .display() .synchronizationInformation() - .assertUnmatched( 1, 0) - .assertUnlinked( 1, 0) - .assertLinked( 3, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) - .end() + .assertUnmatched(1, 0) + .assertUnlinked(1, 0) + .assertLinked(3, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) + .end() .iterativeTaskInformation() - .assertTotalCounts(7, 0) - .end() + .assertTotalCounts(7, 0) + .end() .assertProgress(7); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 6); @@ -466,13 +463,13 @@ public void test155ImportFromResourceDummyAgain() throws Exception { assertTask(task, "task after") .display() .synchronizationInformation() - .assertLinked( 5, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) + .assertLinked(5, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) .end() .iterativeTaskInformation() - .assertTotalCounts(7, 0) - .end() + .assertTotalCounts(7, 0) + .end() .assertProgress(7); assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 3); @@ -548,13 +545,13 @@ public void test160ImportFromResourceDummyLime() throws Exception { assertTask(task, "task after") .display() .synchronizationInformation() - .assertUnmatched( 2, 0) - .assertUnlinked( 1, 0) - .assertLinked( 0, 3) - .assertTotal(3, 3) + .assertUnmatched(2, 0) + .assertUnlinked(1, 0) + .assertLinked(0, 3) + .assertTotal(3, 3) .end() .iterativeTaskInformation() - .assertTotalCounts(3, 0) + .assertTotalCounts(3, 0) .end() .assertProgress(3); @@ -780,7 +777,6 @@ public void test200ReconcileDummy() throws Exception { // Quote is tolerant. The extra values should stay as it is guybrushDummyAccount.addAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_QUOTE_NAME, "I want to be a pirate!"); - // Calypso is protected, this should not reconcile DummyAccount calypsoDummyAccount = getDummyResource().getAccountByUsername(ACCOUNT_CALYPSO_DUMMY_USERNAME); calypsoDummyAccount.replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); @@ -807,12 +803,12 @@ public void test200ReconcileDummy() throws Exception { assertTask(taskAfter, "task after") .display() .synchronizationInformation() - .assertLinked( 5, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) + .assertLinked(5, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) .end() .iterativeTaskInformation() - .assertTotalCounts(9, 0) // protected accounts are processed also in the third stage + .assertTotalCounts(9, 0) // protected accounts are processed also in the third stage .end() .assertProgress(7); // or should be 9? @@ -1068,12 +1064,12 @@ public void test220ReconcileDummyBrokenGuybrush() throws Exception { assertTask(taskAfter, "task after") .display() .synchronizationInformation() - .assertLinked( 5, 5) - .assertProtected( 2, 2) - .assertTotal(7, 7) + .assertLinked(5, 5) + .assertProtected(2, 2) + .assertTotal(7, 7) .end() .iterativeTaskInformation() - .assertTotalCounts(8, 1) + .assertTotalCounts(8, 1) .end() .assertProgress(7); // or should be 9? @@ -1239,14 +1235,14 @@ public void test230ReconcileDummyRename() throws Exception { assertTask(taskAfter, "task after") .display() .synchronizationInformation() - .assertUnmatched(1, 0) - .assertLinked( 4, 5) - .assertDeleted(1, 1) - .assertProtected( 2, 2) - .assertTotal(8, 8) + .assertUnmatched(1, 0) + .assertLinked(4, 5) + .assertDeleted(1, 1) + .assertProtected(2, 2) + .assertTotal(8, 8) .end() .iterativeTaskInformation() - .assertTotalCounts(10, 0) + .assertTotalCounts(10, 0) .end() .assertProgress(8); // or should be 10? @@ -1263,7 +1259,7 @@ public void test230ReconcileDummyRename() throws Exception { assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); // not deleted. reaction=unlink assertRepoShadow(hermanShadowOid) - .assertTombstone(); + .assertTombstone(); assertImportedUserByOid(USER_ADMINISTRATOR_OID); assertImportedUserByOid(USER_JACK_OID); @@ -1396,7 +1392,6 @@ public void test300ReconcileDummyAzureAddAccountOtis() throws Exception { assertDummyAccountAttribute(null, ACCOUNT_CALYPSO_DUMMY_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME_NAME, "Calypso"); - assertEquals("Unexpected number of users", getNumberOfUsers() + 5, users.size()); display("Dummy resource (azure)", dummyResourceAzure.debugDump()); @@ -1446,7 +1441,6 @@ public void test310ReconcileDummyAzureAgain() throws Exception { assertImportedUserByUsername(ACCOUNT_HERMAN_DUMMY_USERNAME); assertImportedUserByUsername(ACCOUNT_HTM_NAME, RESOURCE_DUMMY_OID); - // Otis assertNoImporterUserByUsername(ACCOUNT_OTIS_NAME); assertDummyAccount(RESOURCE_DUMMY_AZURE_NAME, ACCOUNT_OTIS_NAME, ACCOUNT_OTIS_FULLNAME, false); @@ -1528,7 +1522,7 @@ public void test320ReconcileDummyAzureDeleteOtis() throws Exception { "Calypso"); assertRepoShadow(otisShadow.getOid()) - .assertTombstone(); + .assertTombstone(); assertShadows(17); @@ -1546,8 +1540,6 @@ public void test320ReconcileDummyAzureDeleteOtis() throws Exception { */ @Test public void test330ReconcileDummyAzureAddAccountRapp() throws Exception { - final String TEST_NAME = "test330ReconcileDummyAzureAddAccountRapp"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1598,7 +1590,7 @@ public void test330ReconcileDummyAzureAddAccountRapp() throws Exception { assertDummyAccountAttribute(RESOURCE_DUMMY_AZURE_NAME, USER_RAPP_USERNAME, DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_SHIP_NAME, "The crew of The Elaine"); - //Checking password policy + //Checking password policy PrismObject userRapp = findUserByUsername(USER_RAPP_USERNAME); assertNotNull("No user Rapp", userRapp); UserType userTypeRapp = userRapp.asObjectable(); @@ -1615,13 +1607,13 @@ public void test330ReconcileDummyAzureAddAccountRapp() throws Exception { } assertNotNull("No clear text password", stringPassword); - assertTrue("Rapp's password is supposed to contain letter a: "+stringPassword, stringPassword.contains("a")); - + assertTrue("Rapp's password is supposed to contain letter a: " + stringPassword, stringPassword.contains("a")); PrismObject passwordPolicy = getObjectViaRepo(ValuePolicyType.class, PASSWORD_POLICY_LOWER_CASE_ALPHA_AZURE.oid); - boolean isPasswordValid = valuePolicyProcessor.validateValue(stringPassword, passwordPolicy.asObjectable(), - createUserOriginResolver(userRapp), TEST_NAME, task, result); + boolean isPasswordValid = valuePolicyProcessor.validateValue( + stringPassword, passwordPolicy.asObjectable(), + createUserOriginResolver(userRapp), getTestNameShort(), task, result); assertTrue("Password doesn't satisfy password policy, generated password: " + stringPassword, isPasswordValid); // These are protected accounts, they should not be imported @@ -1662,7 +1654,7 @@ public void test332ModifyUserRappAndReconcileDummyAzure() throws Exception { ObjectDelta userRappDelta = prismContext.deltaFactory().object() .createModificationReplaceProperty(UserType.class, USER_RAPP_OID, - UserType.F_ORGANIZATIONAL_UNIT, createPolyString("The six feet under crew")); + UserType.F_ORGANIZATIONAL_UNIT, createPolyString("The six feet under crew")); repositoryService.modifyObject(UserType.class, USER_RAPP_OID, userRappDelta.getModifications(), result); userRappBefore = getUser(USER_RAPP_OID); @@ -1792,7 +1784,6 @@ public void test334AssignRoleCorpseToRappAndReconcileDummyAzure() throws Excepti assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE.oid); } - @Test public void test339ReconcileDummyAzureDeleteRapp() throws Exception { // GIVEN @@ -1856,7 +1847,7 @@ public void test339ReconcileDummyAzureDeleteRapp() throws Exception { "Calypso"); assertRepoShadow(rappShadow.getOid()) - .assertTombstone(); + .assertTombstone(); assertShadows(19); @@ -1868,7 +1859,6 @@ public void test339ReconcileDummyAzureDeleteRapp() throws Exception { assertReconAuditModifications(1, TASK_RECONCILE_DUMMY_AZURE.oid); } - @Test public void test400ReconcileDummyLimeAddAccount() throws Exception { // GIVEN @@ -1968,7 +1958,6 @@ public void test401ReconcileDummyLimeKateOnlyEmpty() throws Exception { display("Dummy resource (lime)", dummyResourceLime.debugDump()); } - @Test public void test402ReconcileDummyLimeKateOnlyGrog() throws Exception { // GIVEN @@ -2580,7 +2569,7 @@ public void test610SearchDummyAccountsNameSubstring() throws Exception { ObjectQueryUtil.createResourceAndObjectClassFilterPrefix(RESOURCE_DUMMY_OID, DUMMY_ACCOUNT_OBJECT_CLASS, prismContext) .and().item(ItemPath.create(ShadowType.F_ATTRIBUTES, SchemaConstants.ICFS_NAME), ObjectFactory.createResourceAttributeDefinition(SchemaConstants.ICFS_NAME, DOMUtil.XSD_STRING, prismContext)) - .contains("s") + .contains("s") .build(); // WHEN @@ -2608,7 +2597,7 @@ public void test900DeleteDummyShadows() throws Exception { dummyAuditService.clear(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); - // WHEN + // WHEN when(); importObjectFromFile(TASK_DELETE_DUMMY_SHADOWS.file); @@ -2633,7 +2622,7 @@ public void test900DeleteDummyShadows() throws Exception { OperationResult opExecResult = opExecResults.get(0); TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 18, opExecResult.getCount()); - assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); + assertTrue("Too many subresults: " + deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); assertUsers(getNumberOfUsers() + 12); @@ -2677,7 +2666,7 @@ public void test910DeleteDummyAccounts() throws Exception { OperationResult opExecResult = opExecResults.get(0); TestUtil.assertSuccess(opExecResult); assertEquals("Wrong exec operation count", 15, opExecResult.getCount()); - assertTrue("Too many subresults: "+deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); + assertTrue("Too many subresults: " + deleteTaskResult.getSubresults().size(), deleteTaskResult.getSubresults().size() < 10); assertUsers(getNumberOfUsers() + 12); @@ -2692,7 +2681,7 @@ private void assertDummyAccountShadows(int expected, boolean raw, Task task, Ope final MutableInt count = new MutableInt(0); ResultHandler handler = (shadow, parentResult) -> { count.increment(); - display("Found",shadow); + display("Found", shadow); return true; }; Collection> options = null; @@ -2700,7 +2689,7 @@ private void assertDummyAccountShadows(int expected, boolean raw, Task task, Ope options = SelectorOptions.createCollection(GetOperationOptions.createRaw()); } modelService.searchObjectsIterative(ShadowType.class, query, handler, options, task, result); - assertEquals("Unexpected number of search results (raw="+raw+")", expected, count.getValue()); + assertEquals("Unexpected number of search results (raw=" + raw + ")", expected, count.getValue()); } private void assertImportAuditModifications(int expectedModifications) { @@ -2708,26 +2697,26 @@ private void assertImportAuditModifications(int expectedModifications) { List auditRecords = dummyAuditService.getRecords(); - int i=0; + int i = 0; int modifications = 0; - for (; i < (auditRecords.size() - 1); i+=2) { + for (; i < (auditRecords.size() - 1); i += 2) { AuditEventRecord requestRecord = auditRecords.get(i); - assertNotNull("No request audit record ("+i+")", requestRecord); - assertEquals("Got this instead of request audit record ("+i+"): "+requestRecord, AuditEventStage.REQUEST, requestRecord.getEventStage()); + assertNotNull("No request audit record (" + i + ")", requestRecord); + assertEquals("Got this instead of request audit record (" + i + "): " + requestRecord, AuditEventStage.REQUEST, requestRecord.getEventStage()); Collection> requestDeltas = requestRecord.getDeltas(); - assertTrue("Unexpected delta in request audit record "+requestRecord, requestDeltas == null || + assertTrue("Unexpected delta in request audit record " + requestRecord, requestDeltas == null || requestDeltas.isEmpty() || (requestDeltas.size() == 1 && requestDeltas.iterator().next().getObjectDelta().isAdd())); - AuditEventRecord executionRecord = auditRecords.get(i+1); - assertNotNull("No execution audit record ("+i+")", executionRecord); - assertEquals("Got this instead of execution audit record ("+i+"): "+executionRecord, AuditEventStage.EXECUTION, executionRecord.getEventStage()); + AuditEventRecord executionRecord = auditRecords.get(i + 1); + assertNotNull("No execution audit record (" + i + ")", executionRecord); + assertEquals("Got this instead of execution audit record (" + i + "): " + executionRecord, AuditEventStage.EXECUTION, executionRecord.getEventStage()); - assertTrue("Empty deltas in execution audit record "+executionRecord, executionRecord.getDeltas() != null && ! executionRecord.getDeltas().isEmpty()); + assertTrue("Empty deltas in execution audit record " + executionRecord, executionRecord.getDeltas() != null && !executionRecord.getDeltas().isEmpty()); modifications++; // check next records while (i < (auditRecords.size() - 2)) { - AuditEventRecord nextRecord = auditRecords.get(i+2); + AuditEventRecord nextRecord = auditRecords.get(i + 2); if (nextRecord.getEventStage() == AuditEventStage.EXECUTION) { // more than one execution record is OK i++; @@ -2749,7 +2738,7 @@ private void assertReconAuditModifications(int expectedModifications, String tas // Record from some other task, skip it auditRecords.removeIf(record -> record.getTaskOid() != null && !record.getTaskOid().equals(taskOid)); - int i=0; + int i = 0; while (i < (auditRecords.size() - 1)) { AuditEventRecord reconStartRecord = auditRecords.get(i); if (reconStartRecord.getEventType() == AuditEventType.EXECUTE_CHANGES_RAW) { @@ -2757,9 +2746,9 @@ private void assertReconAuditModifications(int expectedModifications, String tas continue; } assertNotNull("No reconStartRecord audit record", reconStartRecord); - assertEquals("Wrong stage in reconStartRecord audit record: "+reconStartRecord, AuditEventStage.REQUEST, reconStartRecord.getEventStage()); - assertEquals("Wrong type in reconStartRecord audit record: "+reconStartRecord, AuditEventType.RECONCILIATION, reconStartRecord.getEventType()); - assertTrue("Unexpected delta in reconStartRecord audit record "+reconStartRecord, reconStartRecord.getDeltas() == null || reconStartRecord.getDeltas().isEmpty()); + assertEquals("Wrong stage in reconStartRecord audit record: " + reconStartRecord, AuditEventStage.REQUEST, reconStartRecord.getEventStage()); + assertEquals("Wrong type in reconStartRecord audit record: " + reconStartRecord, AuditEventType.RECONCILIATION, reconStartRecord.getEventType()); + assertTrue("Unexpected delta in reconStartRecord audit record " + reconStartRecord, reconStartRecord.getDeltas() == null || reconStartRecord.getDeltas().isEmpty()); i++; break; } @@ -2767,7 +2756,7 @@ private void assertReconAuditModifications(int expectedModifications, String tas int modifications = 0; for (; i < (auditRecords.size() - 1); ) { AuditEventRecord record = auditRecords.get(i); - assertNotNull("No request audit record ("+i+")", record); + assertNotNull("No request audit record (" + i + ")", record); i++; if (record.getEventStage() == AuditEventStage.EXECUTION && record.getEventType() == AuditEventType.RECONCILIATION) { @@ -2790,25 +2779,25 @@ record = auditRecords.get(i); AuditEventRecord reconStopRecord = auditRecords.get(i); assertNotNull("No reconStopRecord audit record", reconStopRecord); - assertEquals("Wrong stage in reconStopRecord audit record: "+reconStopRecord, AuditEventStage.EXECUTION, reconStopRecord.getEventStage()); - assertEquals("Wrong type in reconStopRecord audit record: "+reconStopRecord, AuditEventType.RECONCILIATION, reconStopRecord.getEventType()); - assertTrue("Unexpected delta in reconStopRecord audit record "+reconStopRecord, reconStopRecord.getDeltas() == null || reconStopRecord.getDeltas().isEmpty()); + assertEquals("Wrong stage in reconStopRecord audit record: " + reconStopRecord, AuditEventStage.EXECUTION, reconStopRecord.getEventStage()); + assertEquals("Wrong type in reconStopRecord audit record: " + reconStopRecord, AuditEventType.RECONCILIATION, reconStopRecord.getEventType()); + assertTrue("Unexpected delta in reconStopRecord audit record " + reconStopRecord, reconStopRecord.getDeltas() == null || reconStopRecord.getDeltas().isEmpty()); } private void assertNoImporterUserByUsername(String username) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(username); - assertNull("User "+username+" sneaked in", user); + assertNull("User " + username + " sneaked in", user); } private void assertImportedUserByOid(String userOid, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = getUser(userOid); - assertNotNull("No user "+userOid, user); + assertNotNull("No user " + userOid, user); assertImportedUser(user, resourceOids); } private PrismObject assertImportedUserByUsername(String username, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject user = findUserByUsername(username); - assertNotNull("No user "+username, user); + assertNotNull("No user " + username, user); assertImportedUser(user, resourceOids); return user; } @@ -2816,7 +2805,7 @@ private PrismObject assertImportedUserByUsername(String username, Stri private void assertImportedUser(PrismObject user, String... resourceOids) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { display("Imported user", user); assertLinks(user, resourceOids.length); - for (String resourceOid: resourceOids) { + for (String resourceOid : resourceOids) { assertAccount(user, resourceOid); } assertAdministrativeStatusEnabled(user); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java index 12889136655..aa8dd916ef3 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelDiscovery.java @@ -194,8 +194,6 @@ protected PrismObject getDefaultActor() { @Test public void test001Sanity() throws Exception { - final String TEST_NAME = "test001Sanity"; - display("Dummy resource azure", dummyResourceSteelBlue); // WHEN @@ -212,8 +210,6 @@ public void test001Sanity() throws Exception { @Test public void test002SanityRefined() throws Exception { - final String TEST_NAME = "test002SanityRefined"; - // WHEN RefinedResourceSchema refinedSchemaSteelBlue = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelBlueType, prismContext); RefinedResourceSchema refinedSchemaSteelGrey = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelGreyType, prismContext); @@ -228,8 +224,6 @@ public void test002SanityRefined() throws Exception { @Test public void test100Synchronize() throws Exception { - final String TEST_NAME = "test100Synchronize"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java index c17274ea029..13fbd6f945f 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestParallelSynchronization.java @@ -164,8 +164,6 @@ protected PrismObject getDefaultActor() { @Test public void test001SanityAzure() throws Exception { - final String TEST_NAME = "test001SanityAzure"; - display("Dummy resource azure", dummyResourceSteelBlue); // WHEN @@ -179,8 +177,6 @@ public void test001SanityAzure() throws Exception { @Test public void test002SanityAzureRefined() throws Exception { - final String TEST_NAME = "test002SanityAzureRefined"; - // WHEN RefinedResourceSchema refinedSchemaAzure = RefinedResourceSchemaImpl.getRefinedSchema(resourceDummySteelBlueType, prismContext); @@ -192,8 +188,6 @@ public void test002SanityAzureRefined() throws Exception { @Test public void test100Synchronize() throws Exception { - final String TEST_NAME = "test100Synchronize"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java index 2fe18ec720d..6ccb2337a2e 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java @@ -9,18 +9,12 @@ import static org.testng.AssertJUnit.assertEquals; import java.io.File; +import java.time.Duration; import java.util.ArrayList; import java.util.Collection; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.security.api.MidPointPrincipal; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -29,27 +23,29 @@ import com.evolveum.midpoint.model.impl.trigger.RecomputeTriggerHandler; import com.evolveum.midpoint.model.intest.AbstractInitializedModelIntegrationTest; import com.evolveum.midpoint.model.intest.TestActivation; -import com.evolveum.midpoint.model.intest.TestTriggerTask; -import com.evolveum.midpoint.model.intest.mapping.TestMapping; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; +import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.security.api.MidPointPrincipal; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DebugUtil; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author Radovan Semancik - * * @see TestActivation - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-intest-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-intest-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestValidityRecomputeTask extends AbstractInitializedModelIntegrationTest { @@ -82,16 +78,11 @@ protected String getValidityScannerTaskFileName() { @Test public void test100ImportValidityScannerTask() throws Exception { - final String TEST_NAME = "test100ImportValidityScannerTask"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - // Pretend that the user was added a long time ago clock.override(LONG_LONG_TIME_AGO); addObject(USER_HERMAN_FILE); - // Make sure that it is effectivelly disabled + // Make sure that it is effectively disabled PrismObject userHermanBefore = getUser(USER_HERMAN_OID); assertEffectiveActivation(userHermanBefore, ActivationStatusType.DISABLED); assertValidityStatus(userHermanBefore, TimeIntervalStatusType.BEFORE); @@ -118,8 +109,6 @@ public void test100ImportValidityScannerTask() throws Exception { @Test public void test110JackAssignJudgeDisabled() throws Exception { - final String TEST_NAME = "test110JackAssignJudgeDisabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -127,45 +116,39 @@ public void test110JackAssignJudgeDisabled() throws Exception { ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.DISABLED); - testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeInvalid(activationType, task, result); } @Test public void test111JackAssignJudgeNotYetValid() throws Exception { - final String TEST_NAME = "test111JackAssignJudgeNotYetValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validFrom = clock.currentTimeXMLGregorianCalendar(); - validFrom.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead + validFrom.add(XmlTypeConverter.createDuration(60 * 60 * 1000)); // one hour ahead activationType.setValidFrom(validFrom); - testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeInvalid(activationType, task, result); } @Test public void test112JackAssignJudgeAfterValidity() throws Exception { - final String TEST_NAME = "test112JackAssignJudgeAfterValidity"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago + validTo.add(XmlTypeConverter.createDuration(-60 * 60 * 1000)); // one hour ago activationType.setValidTo(validTo); - testJackAssignRoleJudgeInvalid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeInvalid(activationType, task, result); } @Test public void test115JackAssignJudgeEnabled() throws Exception { - final String TEST_NAME = "test115JackAssignJudgeEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -173,29 +156,28 @@ public void test115JackAssignJudgeEnabled() throws Exception { ActivationType activationType = new ActivationType(); activationType.setAdministrativeStatus(ActivationStatusType.ENABLED); - testJackAssignRoleJudgeValid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeValid(activationType, task, result); } @Test public void test115JackAssignJudgeValid() throws Exception { - final String TEST_NAME = "test115JackAssignJudgeValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validFrom = clock.currentTimeXMLGregorianCalendar(); - validFrom.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago + validFrom.add(XmlTypeConverter.createDuration(-60 * 60 * 1000)); // one hour ago activationType.setValidFrom(validFrom); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead + validTo.add(XmlTypeConverter.createDuration(60 * 60 * 1000)); // one hour ahead activationType.setValidTo(validTo); - testJackAssignRoleJudgeValid(TEST_NAME, activationType, task, result); + testJackAssignRoleJudgeValid(activationType, task, result); } - private void testJackAssignRoleJudgeValid(final String TEST_NAME, ActivationType activationType, Task task, OperationResult result) throws Exception { + private void testJackAssignRoleJudgeValid( + ActivationType activationType, Task task, OperationResult result) throws Exception { // WHEN when(); @@ -227,7 +209,8 @@ private void testJackAssignRoleJudgeValid(final String TEST_NAME, ActivationType assertNoDummyAccount(null, USER_JACK_USERNAME); } - private void testJackAssignRoleJudgeInvalid(final String TEST_NAME, ActivationType activationType, Task task, OperationResult result) throws Exception { + private void testJackAssignRoleJudgeInvalid( + ActivationType activationType, Task task, OperationResult result) throws Exception { // WHEN when(); @@ -264,11 +247,8 @@ private void assert11xUserOk(PrismObject user) { assertEffectiveActivation(user, ActivationStatusType.ENABLED); } - @Test public void test120JackDisableAssignmentJudge() throws Exception { - final String TEST_NAME = "test120JackDisableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -298,8 +278,6 @@ public void test120JackDisableAssignmentJudge() throws Exception { @Test public void test122JackReplaceNullAdministrativeStatusAssignmentJudge() throws Exception { - final String TEST_NAME = "test122JackReplaceNullAdministrativeStatusAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -322,8 +300,6 @@ public void test122JackReplaceNullAdministrativeStatusAssignmentJudge() throws E @Test public void test123JackDisableAssignmentJudge() throws Exception { - final String TEST_NAME = "test123JackDisableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -346,8 +322,6 @@ public void test123JackDisableAssignmentJudge() throws Exception { @Test public void test124JackEnableAssignmentJudge() throws Exception { - final String TEST_NAME = "test124JackEnableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -370,8 +344,6 @@ public void test124JackEnableAssignmentJudge() throws Exception { @Test public void test125JackDeleteAdministrativeStatusAssignmentJudge() throws Exception { - final String TEST_NAME = "test125JackDeleteAdministrativeStatusAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -396,8 +368,6 @@ public void test125JackDeleteAdministrativeStatusAssignmentJudge() throws Except @Test public void test126JackAddAdministrativeStatusAssignmentJudge() throws Exception { - final String TEST_NAME = "test126JackAddAdministrativeStatusAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -422,8 +392,6 @@ public void test126JackAddAdministrativeStatusAssignmentJudge() throws Exception @Test public void test127JackDeleteActivationAssignmentJudge() throws Exception { - final String TEST_NAME = "test127JackDeleteActivationAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -449,8 +417,6 @@ public void test127JackDeleteActivationAssignmentJudge() throws Exception { @Test public void test128JackAssignmentJudgeValidToSetInvalid() throws Exception { - final String TEST_NAME = "test128JackAssignmentJudgeValidToSetInvalid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -459,7 +425,7 @@ public void test128JackAssignmentJudgeValidToSetInvalid() throws Exception { AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); ActivationType activationType = new ActivationType(); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(-60*60*1000)); // one hour ago + validTo.add(XmlTypeConverter.createDuration(-60 * 60 * 1000)); // one hour ago activationType.setValidTo(validTo); // WHEN @@ -478,8 +444,6 @@ public void test128JackAssignmentJudgeValidToSetInvalid() throws Exception { @Test public void test129JackAssignmentJudgeValidToSetValid() throws Exception { - final String TEST_NAME = "test129JackAssignmentJudgeValidToSetValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -487,7 +451,7 @@ public void test129JackAssignmentJudgeValidToSetValid() throws Exception { assertNoDummyAccount(null, USER_JACK_USERNAME); AssignmentType judgeAssignment = getJudgeAssignment(USER_JACK_OID); XMLGregorianCalendar validTo = clock.currentTimeXMLGregorianCalendar(); - validTo.add(XmlTypeConverter.createDuration(60*60*1000)); // one hour ahead + validTo.add(XmlTypeConverter.createDuration(60 * 60 * 1000)); // one hour ahead // WHEN when(); @@ -520,8 +484,6 @@ private AssignmentType getJudgeAssignment(String userOid) throws ObjectNotFoundE */ @Test public void test130BarbossaAssignJudgeEnabled() throws Exception { - final String TEST_NAME = "test130BarbossaAssignJudgeEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -565,8 +527,6 @@ public void test130BarbossaAssignJudgeEnabled() throws Exception { @Test public void test131BarbossaAssignSailorEnabled() throws Exception { - final String TEST_NAME = "test131BarbossaAssignSailorEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -606,8 +566,6 @@ public void test131BarbossaAssignSailorEnabled() throws Exception { @Test public void test132BarbossaDisableAssignmentJudge() throws Exception { - final String TEST_NAME = "test132BarbossaDisableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -646,8 +604,6 @@ public void test132BarbossaDisableAssignmentJudge() throws Exception { @Test public void test133BarbossaDisableAssignmentSailor() throws Exception { - final String TEST_NAME = "test133BarbossaDisableAssignmentSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -681,8 +637,6 @@ public void test133BarbossaDisableAssignmentSailor() throws Exception { @Test public void test134BarbossaEnableAssignmentJudge() throws Exception { - final String TEST_NAME = "test134BarbossaEnableAssignmentJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -718,8 +672,6 @@ public void test134BarbossaEnableAssignmentJudge() throws Exception { @Test public void test135BarbossaEnableAssignmentSailor() throws Exception { - final String TEST_NAME = "test135BarbossaEnableAssignmentSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -755,8 +707,6 @@ public void test135BarbossaEnableAssignmentSailor() throws Exception { @Test public void test136BarbossaDisableBothAssignments() throws Exception { - final String TEST_NAME = "test136BarbossaDisableBothAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -771,8 +721,8 @@ public void test136BarbossaDisableBothAssignments() throws Exception { AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create(UserType.F_ASSIGNMENT, sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); // WHEN when(); @@ -800,8 +750,6 @@ public void test136BarbossaDisableBothAssignments() throws Exception { @Test public void test137BarbossaEnableBothAssignments() throws Exception { - final String TEST_NAME = "test137BarbossaEnableBothAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -819,11 +767,11 @@ public void test137BarbossaEnableBothAssignments() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.ENABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.ENABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.ENABLED); // WHEN when(); @@ -860,8 +808,6 @@ public void test137BarbossaEnableBothAssignments() throws Exception { */ @Test public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { - final String TEST_NAME = "test139BarbossaDisableBothAssignmentsUnassign"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -883,11 +829,11 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); @@ -939,8 +885,6 @@ public void test139BarbossaDisableBothAssignmentsUnassign() throws Exception { */ @Test public void test140BarbossaAssignRedJudgeEnabled() throws Exception { - final String TEST_NAME = "test140BarbossaAssignRedJudgeEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -988,8 +932,6 @@ public void test140BarbossaAssignRedJudgeEnabled() throws Exception { @Test public void test141BarbossaAssignRedSailorEnabled() throws Exception { - final String TEST_NAME = "test141BarbossaAssignRedSailorEnabled"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1029,8 +971,6 @@ public void test141BarbossaAssignRedSailorEnabled() throws Exception { @Test public void test142BarbossaDisableAssignmentRedJudge() throws Exception { - final String TEST_NAME = "test142BarbossaDisableAssignmentRedJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1069,8 +1009,6 @@ public void test142BarbossaDisableAssignmentRedJudge() throws Exception { @Test public void test143BarbossaDisableAssignmentRedSailor() throws Exception { - final String TEST_NAME = "test143BarbossaDisableAssignmentRedSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1108,8 +1046,6 @@ public void test143BarbossaDisableAssignmentRedSailor() throws Exception { @Test public void test144BarbossaEnableAssignmentRedJudge() throws Exception { - final String TEST_NAME = "test144BarbossaEnableAssignmentRedJudge"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1145,8 +1081,6 @@ public void test144BarbossaEnableAssignmentRedJudge() throws Exception { @Test public void test145BarbossaEnableAssignmentRedSailor() throws Exception { - final String TEST_NAME = "test145BarbossaEnableAssignmentRedSailor"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1182,8 +1116,6 @@ public void test145BarbossaEnableAssignmentRedSailor() throws Exception { @Test public void test146BarbossaDisableBothRedAssignments() throws Exception { - final String TEST_NAME = "test146BarbossaDisableBothRedAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1201,11 +1133,11 @@ public void test146BarbossaDisableBothRedAssignments() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); // WHEN when(); @@ -1237,8 +1169,6 @@ public void test146BarbossaDisableBothRedAssignments() throws Exception { @Test public void test147BarbossaEnableBothRedAssignments() throws Exception { - final String TEST_NAME = "test147BarbossaEnableBothRedAssignments"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1256,11 +1186,11 @@ public void test147BarbossaEnableBothRedAssignments() throws Exception { ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.ENABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.ENABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.ENABLED); // WHEN when(); @@ -1297,8 +1227,6 @@ public void test147BarbossaEnableBothRedAssignments() throws Exception { */ @Test public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception { - final String TEST_NAME = "test149BarbossaDisableBothRedAssignmentsUnassign"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1317,11 +1245,11 @@ public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception AssignmentType.F_ACTIVATION, ActivationType.F_ADMINISTRATIVE_STATUS), ActivationStatusType.DISABLED); objectDelta.addModificationReplaceProperty(ItemPath.create( - UserType.F_ASSIGNMENT, - sailorAssignment.getId(), - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - ActivationStatusType.DISABLED); + UserType.F_ASSIGNMENT, + sailorAssignment.getId(), + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + ActivationStatusType.DISABLED); modelService.executeChanges(MiscSchemaUtil.createCollection(objectDelta), null, task, result); @@ -1373,15 +1301,9 @@ public void test149BarbossaDisableBothRedAssignmentsUnassign() throws Exception assertNotAuthorized(principal, AUTZ_PUNISH_URL); } - @Test public void test190HermanGoesInvalid() throws Exception { - final String TEST_NAME = "test190HermanGoesInvalid"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); PrismObject userHermanBefore = getUser(USER_HERMAN_OID); @@ -1413,9 +1335,6 @@ public void test190HermanGoesInvalid() throws Exception { @Test public void test200ImportTriggerScannerTask() throws Exception { // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - XMLGregorianCalendar startCal = clock.currentTimeXMLGregorianCalendar(); /// WHEN @@ -1439,10 +1358,8 @@ public void test200ImportTriggerScannerTask() throws Exception { */ @Test public void test205AccountRedElaineDisable() throws Exception { - final String TEST_NAME = "test205AccountRedElaineDisable"; - // GIVEN - Task task = taskManager.createTaskInstance(TestActivation.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -1464,10 +1381,8 @@ public void test205AccountRedElaineDisable() throws Exception { */ @Test public void test210JackAssignAndUnassignAccountRed() throws Exception { - final String TEST_NAME = "test210JackAssignAndUnassignAccountRed"; - // GIVEN - Task task = taskManager.createTaskInstance(TestMapping.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // assign @@ -1521,12 +1436,7 @@ public void test210JackAssignAndUnassignAccountRed() throws Exception { */ @Test public void test215JackDummyAccountDeleteAfterMonth() throws Exception { - final String TEST_NAME = "test215JackDummyAccountDeleteAfterMonth"; - // GIVEN - Task task = taskManager.createTaskInstance(TestMapping.class.getName() + "." + TEST_NAME); - OperationResult result = task.getResult(); - XMLGregorianCalendar time = clock.currentTimeXMLGregorianCalendar(); // A month and a day, to make sure we move past the trigger time.add(XmlTypeConverter.createDuration(true, 0, 1, 1, 0, 0, 0)); @@ -1545,8 +1455,6 @@ public void test215JackDummyAccountDeleteAfterMonth() throws Exception { @Test public void test220AddDrake() throws Exception { - final String TEST_NAME = "test220AddDrake"; - XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); display("Start", start); @@ -1610,8 +1518,6 @@ public void test220AddDrake() throws Exception { @Test public void test222Drake4DaysBeforeValidFrom() throws Exception { - final String TEST_NAME = "test222Drake4DaysBeforeValidFrom"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidFrom.clone(); start.add(XmlTypeConverter.createDuration(false, 0, 0, 4, 0, 0, 0)); clock.override(start); @@ -1637,8 +1543,6 @@ public void test222Drake4DaysBeforeValidFrom() throws Exception { @Test public void test224Drake1DaysAfterValidFrom() throws Exception { - final String TEST_NAME = "test224Drake1DaysAfterValidFrom"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidFrom.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 1, 0, 0, 0)); clock.override(start); @@ -1663,8 +1567,6 @@ public void test224Drake1DaysAfterValidFrom() throws Exception { @Test public void test226Drake1DayBeforeValidTo() throws Exception { - final String TEST_NAME = "test226Drake1DayBeforeValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(false, 0, 0, 1, 0, 0, 0)); clock.override(start); @@ -1689,8 +1591,6 @@ public void test226Drake1DayBeforeValidTo() throws Exception { @Test public void test228Drake1DayAfterValidTo() throws Exception { - final String TEST_NAME = "test228Drake1DayAfterValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 1, 0, 0, 0)); clock.override(start); @@ -1716,8 +1616,6 @@ public void test228Drake1DayAfterValidTo() throws Exception { @Test public void test230Drake20DaysAfterValidTo() throws Exception { - final String TEST_NAME = "test230Drake20DaysAfterValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 20, 0, 0, 0)); clock.override(start); @@ -1743,8 +1641,6 @@ public void test230Drake20DaysAfterValidTo() throws Exception { @Test public void test232Drake40DaysAfterValidTo() throws Exception { - final String TEST_NAME = "test232Drake40DaysAfterValidTo"; - XMLGregorianCalendar start = (XMLGregorianCalendar) drakeValidTo.clone(); start.add(XmlTypeConverter.createDuration(true, 0, 0, 40, 0, 0, 0)); clock.override(start); @@ -1771,8 +1667,6 @@ public void test232Drake40DaysAfterValidTo() throws Exception { */ @Test public void test250CheckAccountRedElaine() throws Exception { - final String TEST_NAME = "test250CheckAccountRedElaine"; - // GIVEN // WHEN @@ -1789,18 +1683,16 @@ public void test250CheckAccountRedElaine() throws Exception { @Test public void test300HermanAssignJudgeNotYetValid() throws Exception { - final String TEST_NAME = "test300HermanAssignJudgeNotYetValid"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); ActivationType activationType = new ActivationType(); judgeAssignmentValidFrom = clock.currentTimeXMLGregorianCalendar(); - judgeAssignmentValidFrom.add(XmlTypeConverter.createDuration(10*60*1000)); // 10 minutes ahead + judgeAssignmentValidFrom.add(XmlTypeConverter.createDuration(10 * 60 * 1000)); // 10 minutes ahead activationType.setValidFrom(judgeAssignmentValidFrom); judgeAssignmentValidTo = clock.currentTimeXMLGregorianCalendar(); - judgeAssignmentValidTo.add(XmlTypeConverter.createDuration(30*60*1000)); // 30 minutes ahead + judgeAssignmentValidTo.add(XmlTypeConverter.createDuration(30 * 60 * 1000)); // 30 minutes ahead activationType.setValidTo(judgeAssignmentValidTo); display("Assignment validFrom", judgeAssignmentValidFrom); display("Assignment validTo", judgeAssignmentValidTo); @@ -1816,12 +1708,7 @@ public void test300HermanAssignJudgeNotYetValid() throws Exception { @Test public void test310HermanAssignJudgeBecomesValid() throws Exception { - final String TEST_NAME = "test310HermanAssignJudgeBecomesValid"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - PrismObject user = getUser(USER_HERMAN_OID); display("User before", user); XMLGregorianCalendar start = (XMLGregorianCalendar) judgeAssignmentValidFrom.clone(); @@ -1833,19 +1720,14 @@ public void test310HermanAssignJudgeBecomesValid() throws Exception { // just wait waitForValidityNextRunAssertSuccess(); - assertRoleJudgeValid(TEST_NAME, task, result); + assertRoleJudgeValid(); } @Test public void test315HermanAssignJudgeBecomesInValid() throws Exception { - final String TEST_NAME = "test315HermanAssignJudgeBecomesInValid"; - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - XMLGregorianCalendar start = (XMLGregorianCalendar) judgeAssignmentValidTo.clone(); - start.add(XmlTypeConverter.createDuration(1*60*1000)); + start.add(XmlTypeConverter.createDuration(Duration.ofMinutes(1).toMillis())); clock.override(start); display("Start", start); @@ -1853,17 +1735,17 @@ public void test315HermanAssignJudgeBecomesInValid() throws Exception { // just wait waitForValidityNextRunAssertSuccess(); - assertRoleJudgeInValid(TEST_NAME, task, result); + assertRoleJudgeInValid(); } - private void assertRoleJudgeValid(final String TEST_NAME, Task task, OperationResult result) throws Exception { + private void assertRoleJudgeValid() throws Exception { assertDummyAccount(null, USER_HERMAN_USERNAME); PrismObject user = getUser(USER_HERMAN_OID); display("User after", user); assertLinks(user, 1); } - private void assertRoleJudgeInValid(final String TEST_NAME, Task task, OperationResult result) throws Exception { + private void assertRoleJudgeInValid() throws Exception { assertNoDummyAccount(null, USER_HERMAN_USERNAME); PrismObject user = getUser(USER_HERMAN_OID); display("User after", user); @@ -1881,12 +1763,12 @@ private void modifyAssignmentAdministrativeStatus(String userOid, long assignmen task, result); } else { modifyObjectReplaceProperty(UserType.class, userOid, - ItemPath.create( - UserType.F_ASSIGNMENT, - assignmentId, - AssignmentType.F_ACTIVATION, - ActivationType.F_ADMINISTRATIVE_STATUS), - task, result, status); + ItemPath.create( + UserType.F_ASSIGNMENT, + assignmentId, + AssignmentType.F_ACTIVATION, + ActivationType.F_ADMINISTRATIVE_STATUS), + task, result, status); } } From bd0ee6a2115b13c96b8488ca0382a87101f4f8d2 Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Fri, 6 Mar 2020 22:00:43 +0100 Subject: [PATCH 21/55] Fix test for MID-6045 --- .../evolveum/midpoint/model/intest/TestUserTemplate.java | 7 +++++-- 1 file changed, 5 insertions(+), 2 deletions(-) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java index 184b5c70d22..f8ccdb4bb36 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestUserTemplate.java @@ -144,11 +144,12 @@ public void test000Sanity() throws Exception { assertNotNull("no system config", systemConfiguration); List defaultObjectPolicyConfiguration = systemConfiguration.asObjectable().getDefaultObjectPolicyConfiguration(); assertNotNull("No object policy", defaultObjectPolicyConfiguration); - assertEquals("Wrong object policy size", 6, defaultObjectPolicyConfiguration.size()); // last two are conflict resolution rules + assertEquals("Wrong object policy size", 7, defaultObjectPolicyConfiguration.size()); // last two are conflict resolution rules assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, null, USER_TEMPLATE_COMPLEX_OID); assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_MAROONED, USER_TEMPLATE_MAROONED_OID); assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_USELESS, USER_TEMPLATE_USELESS_OID); assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_MID_5892, USER_TEMPLATE_MID_5892.oid); + assertObjectTemplate(defaultObjectPolicyConfiguration, UserType.COMPLEX_TYPE, SUBTYPE_MID_6045, USER_TEMPLATE_MID_6045.oid); assertRoles(getNumberOfRoles()); } @@ -253,7 +254,7 @@ public void test101ModifyUserEmployeeTypePirate() throws Exception { /** * Switch employeeType from PIRATE to BUCCANEER. This makes one condition to go false and the other to go - * true. For the same role assignement value. So nothing should be changed. + * true. For the same role assignment value. So nothing should be changed. */ @Test public void test102ModifyUserEmployeeTypeBuccaneer() throws Exception { @@ -3571,6 +3572,8 @@ public void test990SpecialTimedMapping() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); + clock.resetOverride(); + XMLGregorianCalendar firstTriggerTime = XmlTypeConverter.fromNow("PT1M"); UserType user = new UserType(prismContext) From 0a1a9f77a66473e48b46ec9161c4aa09c79dc746 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Sat, 7 Mar 2020 22:07:20 +0100 Subject: [PATCH 22/55] WebComponentUtil,ShadowAssociationWrapperFI: fixed "assoc(i)ation" typo --- .../midpoint/gui/api/util/WebComponentUtil.java | 9 +++++---- .../factory/ShadowAssociationWrapperFactoryImpl.java | 12 ++++++------ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java index 995f3ae9d3e..4d1749f03b7 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java @@ -3013,15 +3013,16 @@ public static boolean isAllNulls(Iterable array) { return StreamSupport.stream(array.spliterator(), true).allMatch(o -> o == null); } - public static ObjectFilter createAssociationShadowRefFilter(RefinedAssociationDefinition refinedAssocationDefinition, PrismContext prismContext, - String resourceOid){ + public static ObjectFilter createAssociationShadowRefFilter( + RefinedAssociationDefinition refinedAssociationDefinition, + PrismContext prismContext, String resourceOid) { S_FilterEntryOrEmpty atomicFilter = prismContext.queryFor(ShadowType.class); List orFilterClauses = new ArrayList<>(); - refinedAssocationDefinition.getIntents() + refinedAssociationDefinition.getIntents() .forEach(intent -> orFilterClauses.add(atomicFilter.item(ShadowType.F_INTENT).eq(intent).buildFilter())); OrFilter intentFilter = prismContext.queryFactory().createOr(orFilterClauses); - AndFilter filter = (AndFilter) atomicFilter.item(ShadowType.F_KIND).eq(refinedAssocationDefinition.getKind()).and() + AndFilter filter = (AndFilter) atomicFilter.item(ShadowType.F_KIND).eq(refinedAssociationDefinition.getKind()).and() .item(ShadowType.F_RESOURCE_REF).ref(resourceOid, ResourceType.COMPLEX_TYPE).buildFilter(); filter.addCondition(intentFilter); return filter; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java index d527a3a74f1..c0026150ead 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java @@ -176,9 +176,9 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context); List> items = new ArrayList<>(); - for (RefinedAssociationDefinition refinedAssocationDefinition: refinedAssociationDefinitions) { + for (RefinedAssociationDefinition refinedAssociationDefinition: refinedAssociationDefinitions) { MutablePrismReferenceDefinition shadowRefDef = prismContext - .definitionFactory().createReferenceDefinition(refinedAssocationDefinition.getName(), ObjectReferenceType.COMPLEX_TYPE); + .definitionFactory().createReferenceDefinition(refinedAssociationDefinition.getName(), ObjectReferenceType.COMPLEX_TYPE); shadowRefDef.toMutable().setMaxOccurs(-1); shadowRefDef.setTargetTypeName(ShadowType.COMPLEX_TYPE); PrismReference shadowAss = shadowRefDef.instantiate(); @@ -186,7 +186,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p for (PrismContainerValue associationValue : association.getValues()) { if (association.getDefinition().getCompileTimeClass().equals(ShadowAssociationType.class)) { ShadowAssociationType shadowAssociation = (ShadowAssociationType)associationValue.asContainerable(); - if (shadowAssociation.getName().equals(refinedAssocationDefinition.getName())) { + if (shadowAssociation.getName().equals(refinedAssociationDefinition.getName())) { itemPath = associationValue.getPath(); shadowAss.add(associationValue.findReference(ShadowAssociationType.F_SHADOW_REF).getValue().clone()); } @@ -197,9 +197,9 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p itemPath = ShadowType.F_ASSOCIATION; } - String displayName = refinedAssocationDefinition.getDisplayName(); + String displayName = refinedAssociationDefinition.getDisplayName(); if (StringUtils.isBlank(displayName)) { - displayName = refinedAssocationDefinition.getName().getLocalPart(); + displayName = refinedAssociationDefinition.getName().getLocalPart(); } ShadowAssociationReferenceWrapperImpl item = new ShadowAssociationReferenceWrapperImpl(shadowValueWrapper, shadowAss, @@ -221,7 +221,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p refValues.add(refValue); } item.getValues().addAll((Collection)refValues); - item.setFilter(WebComponentUtil.createAssociationShadowRefFilter(refinedAssocationDefinition, + item.setFilter(WebComponentUtil.createAssociationShadowRefFilter(refinedAssociationDefinition, prismContext, resource.getOid())); // item.setReadOnly(true); From 0ec88584bc7fbb90de1a38be3dead2d1d3ffc88e Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Sat, 7 Mar 2020 23:12:15 +0100 Subject: [PATCH 23/55] more test cleanup, more TEST_NAME variables gone --- .../lex/AbstractJsonLexicalProcessorTest.java | 31 +- .../lex/AbstractLexicalProcessorTest.java | 13 +- .../evolveum/midpoint/report/TestReport.java | 41 +- .../midpoint/report/TestReportSafe.java | 10 +- .../midpoint/report/TestReportWebService.java | 39 +- .../impl/TestConnectorDiscovery.java | 8 +- .../impl/TestConnectorManager.java | 32 +- .../provisioning/impl/dummy/TestDummy.java | 357 ++++++------------ .../impl/dummy/TestDummyCaching.java | 73 ++-- .../impl/dummy/TestDummyExtra.java | 10 +- .../impl/dummy/TestDummyNegative.java | 20 +- .../TestDummyResourceAndSchemaCaching.java | 71 ++-- .../impl/dummy/TestDummySchemaless.java | 106 ++---- .../manual/AbstractManualResourceTest.java | 31 -- .../impl/opendj/TestOpenDjDumber.java | 9 +- .../common/commandline/TestCommandLine.java | 8 +- .../midpoint/repo/sql/ResourceModifyTest.java | 33 +- .../testing/rest/TestAbstractRestService.java | 245 +++--------- .../TestRestServiceProxyAuthentication.java | 10 - .../midpoint/testing/sanity/TestSanity.java | 136 ++----- 20 files changed, 345 insertions(+), 938 deletions(-) diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java index 94e19f8820a..9d753de2933 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractJsonLexicalProcessorTest.java @@ -7,19 +7,20 @@ package com.evolveum.midpoint.prism.lex; -import com.evolveum.midpoint.prism.impl.lex.LexicalProcessor; -import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.prism.impl.xnode.RootXNodeImpl; -import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.exception.SchemaException; -import org.testng.annotations.Test; +import static org.assertj.core.api.Assertions.assertThat; +import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.fail; import java.util.ArrayList; import java.util.List; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.fail; +import org.testng.annotations.Test; + +import com.evolveum.midpoint.prism.impl.lex.LexicalProcessor; +import com.evolveum.midpoint.prism.impl.xnode.RootXNodeImpl; +import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.util.DebugUtil; +import com.evolveum.midpoint.util.exception.SchemaException; /** * @author mederly @@ -68,7 +69,8 @@ public void testParseObjectsIteratively_2_Wrong() throws Exception { System.out.println("Parsed objects (standard way):"); System.out.println(DebugUtil.debugDump(nodesStandard)); - assertFalse("Nodes are not different", nodesStandard.equals(nodes)); + assertThat(nodesStandard).withFailMessage("Nodes are not different") + .isNotEqualTo(nodes); } @Test @@ -98,16 +100,11 @@ public void testParseObjectsIteratively_2_Wrong_2() throws Exception { @Test public void testParseObjectsIteratively_9_listSingle() throws Exception { - final String TEST_NAME = "testParseObjectsIteratively_9_listSingle"; - - standardTest(TEST_NAME, OBJECTS_9_LIST_SINGLE, 1); + standardTest(OBJECTS_9_LIST_SINGLE, 1); } @Test public void testParseObjectsIteratively_10_listOfLists() throws Exception { - final String TEST_NAME = "testParseObjectsIteratively_10_listOfLists"; - - standardTest(TEST_NAME, OBJECTS_10_LIST_OF_LISTS, 3); + standardTest(OBJECTS_10_LIST_OF_LISTS, 3); } - } diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java index d322a9b3e56..48fac86fcc8 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/lex/AbstractLexicalProcessorTest.java @@ -86,7 +86,7 @@ protected File getFile(String baseName) { @Test public void testParseUserToPrism() throws Exception { // GIVEN - LexicalProcessor lexicalProcessor = createParser(); + LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); // WHEN (parse to xnode) @@ -182,7 +182,7 @@ public void testParseUserRoundTrip() throws Exception { @Test public void testParseResourceRumToPrism() throws Exception { // GIVEN - LexicalProcessor lexicalProcessor = createParser(); + LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); // WHEN (parse to xnode) @@ -331,7 +331,7 @@ protected void validateResourceSchema(String dataString, PrismContext prismConte @Test(enabled = false) public void testParseEventHandler() throws Exception { // GIVEN - LexicalProcessor lexicalProcessor = createParser(); + LexicalProcessor lexicalProcessor = createParser(); PrismContext prismContext = PrismTestUtil.getPrismContext(); // WHEN (parse to xnode) @@ -356,9 +356,7 @@ public void testParseEventHandler() throws Exception { @Test public void testParseObjectsIteratively_1() throws Exception { - final String TEST_NAME = "testParseObjectsIteratively_1"; - - List nodes = standardTest(TEST_NAME, OBJECTS_1, 3); + List nodes = standardTest(OBJECTS_1, 3); final String NS_C = "http://midpoint.evolveum.com/xml/ns/public/common/common-3"; nodes.forEach(n -> assertEquals("Wrong namespace", NS_C, n.getRootElementName().getNamespaceURI())); @@ -367,7 +365,8 @@ public void testParseObjectsIteratively_1() throws Exception { assertEquals("Wrong namespace for node 3", NS_C, getFirstElementNS(nodes, 2)); } - protected List standardTest(String TEST_NAME, String fileName, int expectedCount) throws SchemaException, IOException { + protected List standardTest(String fileName, int expectedCount) + throws SchemaException, IOException { // GIVEN LexicalProcessor lexicalProcessor = createParser(); diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java index 1a3d9be1c5f..ff91897d09b 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java @@ -67,8 +67,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ReportUserList() throws Exception { - final String TEST_NAME = "test100ReportUserList"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -98,8 +96,7 @@ public void test100ReportUserList() throws Exception { */ @Test public void test110ReportUserListExpressionsCsv() throws Exception { - final String TEST_NAME = "test110ReportUserListExpressionsCsv"; - testReportListUsersCsv(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_CSV_OID); + testReportListUsersCsv(REPORT_USER_LIST_EXPRESSIONS_CSV_OID); } /** @@ -109,8 +106,7 @@ public void test110ReportUserListExpressionsCsv() throws Exception { */ @Test public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception { - final String TEST_NAME = "test112ReportUserListExpressionsPoisonousQueryCsv"; - testReportListUsersCsv(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); + testReportListUsersCsv(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); } /** @@ -120,14 +116,11 @@ public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception */ @Test public void test114ReportUserListExpressionsPoisonousFieldCsv() throws Exception { - final String TEST_NAME = "test114ReportUserListExpressionsPoisonousFieldCsv"; - testReportListUsersCsv(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); + testReportListUsersCsv(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); } @Test public void test200ReportUserListScript() throws Exception { - final String TEST_NAME = "test200ReportUserListScript"; - if (!isOsUnix()) { displaySkip(); return; @@ -165,37 +158,35 @@ public void test200ReportUserListScript() throws Exception { */ @Test public void test300ReportAuditLegacy() throws Exception { - final String TEST_NAME = "test300ReportAuditLegacy"; - testReportAuditCsvSuccess(TEST_NAME, REPORT_AUDIT_CSV_LEGACY_OID); + testReportAuditCsvSuccess(REPORT_AUDIT_CSV_LEGACY_OID); } @Test public void test310ReportAudit() throws Exception { - final String TEST_NAME = "test310ReportAudit"; - testReportAuditCsvSuccess(TEST_NAME, REPORT_AUDIT_CSV_OID); + testReportAuditCsvSuccess(REPORT_AUDIT_CSV_OID); } - protected void testReportListUsersCsv(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportListUsersCsv(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, false); + PrismObject finishedTask = runReport(report, false); assertSuccess("Finished report task result", finishedTask.asObjectable().getResult()); checkCsvUserReport(report); } - protected void testReportListUsersCsvFailure(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportListUsersCsvFailure(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, true); + PrismObject finishedTask = runReport(report, true); assertFailure("Finished report task result", finishedTask.asObjectable().getResult()); assertNoCsvReport(report); } - protected PrismObject runReport(final String TEST_NAME, PrismObject report, boolean errorOk) throws Exception { + protected PrismObject runReport(PrismObject report, boolean errorOk) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); @@ -234,34 +225,34 @@ protected void checkCsvUserReport(PrismObject report) throws IOExcep assertEquals("Unexpected number of report lines", currentUsers.size() + 1, lines.size()); } - protected void assertNoCsvReport(PrismObject report) throws IOException, SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void assertNoCsvReport(PrismObject report) { File outputFile = findOutputFile(report); display("Found report file (expected null)", outputFile); assertNull("Unexpected output file for "+report+": "+outputFile, outputFile); } - protected void testReportAuditCsvSuccess(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportAuditCsvSuccess(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, false); + PrismObject finishedTask = runReport(report, false); assertSuccess("Report task result", finishedTask.asObjectable().getResult()); checkCsvAuditReport(report); } - protected void testReportAuditCsvFailure(final String TEST_NAME, String reportOid) throws Exception { + protected void testReportAuditCsvFailure(String reportOid) throws Exception { PrismObject report = getObject(ReportType.class, reportOid); - PrismObject finishedTask = runReport(TEST_NAME, report, true); + PrismObject finishedTask = runReport(report, true); assertFailure("Finished report task result", finishedTask.asObjectable().getResult()); assertNoCsvReport(report); } - protected void checkCsvAuditReport(PrismObject report) throws IOException, SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { + protected void checkCsvAuditReport(PrismObject report) throws IOException { File outputFile = findOutputFile(report); display("Found report file", outputFile); assertNotNull("No output file for "+report, outputFile); diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java index f353f37c08c..8c784a2029f 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportSafe.java @@ -41,8 +41,7 @@ protected File getSystemConfigurationFile() { @Test @Override public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception { - final String TEST_NAME = "test110ReportUserListExpressionsCsv"; - testReportListUsersCsvFailure(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); + testReportListUsersCsvFailure(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_QUERY_CSV_OID); } /** @@ -52,8 +51,7 @@ public void test112ReportUserListExpressionsPoisonousQueryCsv() throws Exception */ @Test public void test114ReportUserListExpressionsPoisonousFieldCsv() throws Exception { - final String TEST_NAME = "test114ReportUserListExpressionsPoisonousFieldCsv"; - testReportListUsersCsvFailure(TEST_NAME, REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); + testReportListUsersCsvFailure(REPORT_USER_LIST_EXPRESSIONS_POISONOUS_FIELD_CSV_OID); } /** @@ -62,8 +60,6 @@ public void test114ReportUserListExpressionsPoisonousFieldCsv() throws Exception */ @Test public void test300ReportAuditLegacy() throws Exception { - final String TEST_NAME = "test300ReportAuditLegacy"; - testReportAuditCsvFailure(TEST_NAME, REPORT_AUDIT_CSV_LEGACY_OID); + testReportAuditCsvFailure(REPORT_AUDIT_CSV_LEGACY_OID); } - } diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java index 0b22a72d490..b2ef7806060 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReportWebService.java @@ -21,12 +21,7 @@ import com.evolveum.midpoint.schema.SearchResultList; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; @@ -60,16 +55,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @Test - public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - + public void test000Sanity() { assertNotNull("No web service", reportWebService); } @Test public void test100ProcessReportUserList() throws Exception { - final String TEST_NAME = "test100ProcessReportUserList"; - String query = createAllQueryString(UserType.class); RemoteReportParametersType parameters = createReportParameters(); @@ -79,15 +70,13 @@ public void test100ProcessReportUserList() throws Exception { // THEN then(); - display("Returned user list ("+userList.getObject().size()+" objects)", userList); + display("Returned user list (" + userList.getObject().size() + " objects)", userList); assertUserList(userList); } @Test - public void test110ProcessReportUserListNoReportOid() throws Exception { - final String TEST_NAME = "test110ProcessReportUserListNoReportOid"; - + public void test110ProcessReportUserListNoReportOid() { String query = createAllQueryString(UserType.class); RemoteReportParametersType parameters = createReportParameters(); @@ -107,9 +96,7 @@ public void test110ProcessReportUserListNoReportOid() throws Exception { } @Test - public void test112ProcessReportUserListInvalidReportOid() throws Exception { - final String TEST_NAME = "test112ProcessReportUserListInvalidReportOid"; - + public void test112ProcessReportUserListInvalidReportOid() { String query = createAllQueryString(UserType.class); RemoteReportParametersType parameters = createReportParameters(); @@ -133,8 +120,6 @@ public void test112ProcessReportUserListInvalidReportOid() throws Exception { */ @Test public void test115ProcessReportUserListUnauthorizedReader() throws Exception { - final String TEST_NAME = "test115ProcessReportUserListUnauthorizedReader"; - login(USER_READER_USERNAME); String query = createAllQueryString(UserType.class); @@ -162,8 +147,6 @@ public void test115ProcessReportUserListUnauthorizedReader() throws Exception { */ @Test public void test116ProcessReportUserListUnauthorizedRunner() throws Exception { - final String TEST_NAME = "test116ProcessReportUserListUnauthorizedRunner"; - login(USER_RUNNER_USERNAME); String query = createAllQueryString(UserType.class); @@ -191,8 +174,6 @@ public void test116ProcessReportUserListUnauthorizedRunner() throws Exception { */ @Test public void test119ProcessReportUserListReaderRunner() throws Exception { - final String TEST_NAME = "test119ProcessReportUserListReaderRunner"; - login(USER_READER_RUNNER_USERNAME); String query = createAllQueryString(UserType.class); @@ -211,7 +192,7 @@ public void test119ProcessReportUserListReaderRunner() throws Exception { // THEN then(); - display("Returned user list ("+userList.getObject().size()+" objects)", userList); + display("Returned user list (" + userList.getObject().size() + " objects)", userList); assertUserList(userList); } @@ -219,22 +200,20 @@ public void test119ProcessReportUserListReaderRunner() throws Exception { // TODO: test that violates safe profile private String createAllQueryString(Class type) { - return ""+type.getSimpleName()+""; + return "" + type.getSimpleName() + ""; } private RemoteReportParametersType createReportParameters() { - RemoteReportParametersType parameters = new RemoteReportParametersType(); - return parameters; + return new RemoteReportParametersType(); } private void assertUserList(ObjectListType userList) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = getTestTask(); OperationResult result = task.getResult(); SearchResultList> currentUsers = modelService.searchObjects(UserType.class, null, null, task, result); - display("Current users in midPoint ("+currentUsers.size()+" users)", currentUsers.toString()); + display("Current users in midPoint (" + currentUsers.size() + " users)", currentUsers.toString()); assertEquals("Unexpected number of returned objects", currentUsers.size(), userList.getObject().size()); } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java index d0c04781bff..f9a7383bbcb 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorDiscovery.java @@ -47,9 +47,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test001Connectors() throws Exception { - final String TEST_NAME = "test001Connectors"; - - OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN when(); @@ -91,9 +89,7 @@ public void testListConnectors() throws Exception { @Test public void testSearchConnectorSimple() throws SchemaException { - final String TEST_NAME = "testSearchConnectorSimple"; - OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); PrismObject ldapConnector = findConnectorByType(IntegrationTestTools.LDAP_CONNECTOR_TYPE, result); assertEquals("Type does not match", IntegrationTestTools.LDAP_CONNECTOR_TYPE, ldapConnector.asObjectable().getConnectorType()); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java index c75e77340c4..e571352b298 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/TestConnectorManager.java @@ -6,20 +6,16 @@ */ package com.evolveum.midpoint.provisioning.impl; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.util.Collection; -import com.evolveum.midpoint.prism.util.PrismAsserts; - import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.Test; -import com.evolveum.midpoint.provisioning.api.ProvisioningService; +import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorFactory; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; @@ -34,7 +30,6 @@ public class TestConnectorManager extends AbstractIntegrationTest { private static final String CONNID_FRAMEWORK_VERSION = "1.5.0.10"; - @Autowired private ProvisioningService provisioningService; @Autowired private ConnectorManager connectorManager; @Override @@ -45,10 +40,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @Test - public void test100ListConnectorFactories() throws Exception { - final String TEST_NAME = "test100ListConnectorFactories"; - - OperationResult result = new OperationResult(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); + public void test100ListConnectorFactories() { + OperationResult result = createOperationResult(); // WHEN when(); @@ -58,13 +51,12 @@ public void test100ListConnectorFactories() throws Exception { then(); assertNotNull("Null connector factories", connectorFactories); assertFalse("No connector factories found", connectorFactories.isEmpty()); - display("Found "+connectorFactories.size()+" connector factories"); + display("Found " + connectorFactories.size() + " connector factories"); assertSuccess(result); - for (ConnectorFactory connectorFactory : connectorFactories) { - display("Found connector factory " +connectorFactory, connectorFactory); + display("Found connector factory " + connectorFactory, connectorFactory); } PrismAsserts.assertEqualsUnordered("Wrong connector factories", @@ -74,10 +66,8 @@ public void test100ListConnectorFactories() throws Exception { } @Test - public void test110SelfTest() throws Exception { - final String TEST_NAME = "test100ListConnectorFactories"; - - Task task = taskManager.createTaskInstance(TestConnectorDiscovery.class.getName() + "." + TEST_NAME); + public void test110SelfTest() { + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -90,15 +80,11 @@ public void test110SelfTest() throws Exception { } @Test - public void test120FrameworkVersion() throws Exception { - final String TEST_NAME = "test120FrameworkVersion"; - + public void test120FrameworkVersion() { // WHEN String frameworkVersion = connectorManager.getFrameworkVersion(); // THEN assertEquals("Unexpected framework version", CONNID_FRAMEWORK_VERSION, frameworkVersion); - } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java index cb21b2a2aae..5a2120dec17 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java @@ -123,10 +123,9 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test101AddAccountWithoutName() throws Exception { - final String TEST_NAME = "test101AddAccountWithoutName"; // GIVEN - Task syncTask = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + Task syncTask = getTestTask(); + OperationResult result = syncTask.getResult(); syncServiceMock.reset(); ShadowType account = parseObjectType(ACCOUNT_MORGAN_FILE, ShadowType.class); @@ -207,9 +206,8 @@ public void test101AddAccountWithoutName() throws Exception { */ @Test public void test107AGetModifiedAccountFromCacheMax() throws Exception { - final String TEST_NAME = "test107AGetModifiedAccountFromCacheMax"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -261,9 +259,8 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { */ @Test public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception { - final String TEST_NAME = "test107BGetModifiedAccountFromCacheHighStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -311,9 +308,8 @@ public void test107CSkipCachingForIncompleteAttributes() throws Exception { */ @Test public void test108GetAccountLowStaleness() throws Exception { - final String TEST_NAME = "test106GetModifiedAccount"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); Collection> options = @@ -367,10 +363,8 @@ public void test108GetAccountLowStaleness() throws Exception { */ @Test public void test109ModifiedAccountCleanup() throws Exception { - final String TEST_NAME = "test109ModifiedAccountCleanup"; - // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -407,10 +401,8 @@ public void test109ModifiedAccountCleanup() throws Exception { @Test public void test110SearchIterative() throws Exception { - final String TEST_NAME = "test110SeachIterative"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // Make sure there is an account on resource that the provisioning has // never seen before, so there is no shadow @@ -524,10 +516,8 @@ public boolean handle(PrismObject object, OperationResult parentResu @Test public void test111SeachIterativeNoFetch() throws Exception { - final String TEST_NAME = "test111SeachIterativeNoFetch"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), @@ -578,10 +568,8 @@ public void test111SeachIterativeNoFetch() throws Exception { @Test public void test112SeachIterativeKindIntent() throws Exception { - final String TEST_NAME = "test112SeachIterativeKindIntent"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndKindIntent(RESOURCE_DUMMY_OID, ShadowKindType.ACCOUNT, "default", prismContext); @@ -655,10 +643,8 @@ public void test113SearchAllShadowsInRepository() throws Exception { @Test public void test114SearchAllAccounts() throws Exception { - final String TEST_NAME = "test114SearchAllAccounts"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -685,9 +671,8 @@ public void test114SearchAllAccounts() throws Exception { @Test public void test115CountAllAccounts() throws Exception { - final String TEST_NAME = "test115CountAllAccounts"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -713,10 +698,8 @@ protected Integer getTest115ExpectedCount() { @Test public void test116SearchNullQueryResource() throws Exception { - final String TEST_NAME = "test116SearchNullQueryResource"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN List> allResources = provisioningService.searchObjects(ResourceType.class, @@ -764,10 +747,8 @@ public void test117CountNullQueryResource() throws Exception { */ @Test public void test118SearchAllAccountsLongStaleness() throws Exception { - final String TEST_NAME = "test118SearchAllAccountsLongStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -811,10 +792,8 @@ public void test118SearchAllAccountsLongStaleness() throws Exception { */ @Test public void test119SearchAllAccountsMaxStaleness() throws Exception { - final String TEST_NAME = "test119SearchAllAccountsMaxStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -854,8 +833,6 @@ public void test119SearchAllAccountsMaxStaleness() throws Exception { @Test public void test120ModifyWillReplaceFullname() throws Exception { - final String TEST_NAME = "test120ModifyWillReplaceFullname"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -885,8 +862,6 @@ public void test120ModifyWillReplaceFullname() throws Exception { @Test public void test121ModifyObjectAddPirate() throws Exception { - final String TEST_NAME = "test121ModifyObjectAddPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -919,8 +894,6 @@ public void test121ModifyObjectAddPirate() throws Exception { @Test public void test122ModifyObjectAddCaptain() throws Exception { - final String TEST_NAME = "test122ModifyObjectAddCaptain"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -953,8 +926,6 @@ public void test122ModifyObjectAddCaptain() throws Exception { @Test public void test123ModifyObjectDeletePirate() throws Exception { - final String TEST_NAME = "test123ModifyObjectDeletePirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -990,8 +961,6 @@ public void test123ModifyObjectDeletePirate() throws Exception { */ @Test public void test124ModifyAccountWillAddCaptainAgain() throws Exception { - final String TEST_NAME = "test124ModifyAccountWillAddCaptainAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1026,10 +995,8 @@ public void test124ModifyAccountWillAddCaptainAgain() throws Exception { */ @Test public void test125CompareAccountWillPassword() throws Exception { - final String TEST_NAME = "test125CompareAccountWillPassword"; - - testComparePassword(TEST_NAME, "match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); - testComparePassword(TEST_NAME, "mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); + testComparePassword("match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); + testComparePassword("mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); assertSteadyResource(); } @@ -1039,8 +1006,6 @@ public void test125CompareAccountWillPassword() throws Exception { */ @Test public void test126ModifyAccountWillPassword() throws Exception { - final String TEST_NAME = "test126ModifyAccountWillPassword"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1081,16 +1046,15 @@ public void test126ModifyAccountWillPassword() throws Exception { */ @Test public void test127CompareAccountWillPassword() throws Exception { - final String TEST_NAME = "test125CompareAccountWillPassword"; - - testComparePassword(TEST_NAME, "match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); - testComparePassword(TEST_NAME, "mismatch old password", ACCOUNT_WILL_OID, ACCOUNT_WILL_PASSWORD, getExpectedPasswordComparisonResultMismatch()); - testComparePassword(TEST_NAME, "mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); + testComparePassword("match", ACCOUNT_WILL_OID, accountWillCurrentPassword, getExpectedPasswordComparisonResultMatch()); + testComparePassword("mismatch old password", ACCOUNT_WILL_OID, ACCOUNT_WILL_PASSWORD, getExpectedPasswordComparisonResultMismatch()); + testComparePassword("mismatch", ACCOUNT_WILL_OID, "I woulD NeVeR ever USE this PASSword", getExpectedPasswordComparisonResultMismatch()); assertSteadyResource(); } - protected void testComparePassword(final String TEST_NAME, String tag, String shadowOid, String expectedPassword, ItemComparisonResult expectedResult) throws Exception { + protected void testComparePassword(String tag, String shadowOid, + String expectedPassword, ItemComparisonResult expectedResult) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1115,8 +1079,6 @@ protected void testComparePassword(final String TEST_NAME, String tag, String sh */ @Test public void test129NullAttributeValue() throws Exception { - final String TEST_NAME = "test129NullAttributeValue"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -1143,10 +1105,8 @@ public void test129NullAttributeValue() throws Exception { @Test public void test131AddScript() throws Exception { - final String TEST_NAME = "test131AddScript"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1241,10 +1201,8 @@ public void test132ModifyScript() throws Exception { */ @Test public void test133ModifyScriptNoExec() throws Exception { - final String TEST_NAME = "test133ModifyScriptNoExec"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1282,10 +1240,8 @@ public void test133ModifyScriptNoExec() throws Exception { @Test public void test134DeleteScript() throws Exception { - final String TEST_NAME = "test134DeleteScript"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1318,10 +1274,8 @@ public void test134DeleteScript() throws Exception { @Test public void test135ExecuteScript() throws Exception { - final String TEST_NAME = "test135ExecuteScript"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResource.purgeScriptHistory(); @@ -1348,10 +1302,8 @@ public void test135ExecuteScript() throws Exception { @Test public void test150DisableAccount() throws Exception { - final String TEST_NAME = "test150DisableAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1392,10 +1344,8 @@ public void test150DisableAccount() throws Exception { @Test public void test151SearchDisabledAccounts() throws Exception { - final String TEST_NAME = "test151SearchDisabledAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1424,10 +1374,8 @@ public void test151SearchDisabledAccounts() throws Exception { @Test public void test152ActivationStatusUndefinedAccount() throws Exception { - final String TEST_NAME = "test152ActivationStatusUndefinedAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1460,8 +1408,8 @@ public void test152ActivationStatusUndefinedAccount() throws Exception { delta.checkConsistence(); // check if activation was changed dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); - assertEquals("Wrong dummy account " + transformNameFromResource(ACCOUNT_WILL_USERNAME) + " enabled flag", - null, dummyAccount.isEnabled()); + assertNull("Wrong dummy account " + transformNameFromResource(ACCOUNT_WILL_USERNAME) + " enabled flag", + dummyAccount.isEnabled()); syncServiceMock.assertNotifySuccessOnly(); @@ -1470,10 +1418,8 @@ public void test152ActivationStatusUndefinedAccount() throws Exception { @Test public void test154EnableAccount() throws Exception { - final String TEST_NAME = "test154EnableAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1482,7 +1428,7 @@ public void test154EnableAccount() throws Exception { display("Retrieved account shadow", accountType); DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); - assertEquals("Wrong dummy account enabled flag", null, dummyAccount.isEnabled()); + assertNull("Wrong dummy account enabled flag", dummyAccount.isEnabled()); syncServiceMock.reset(); @@ -1513,10 +1459,8 @@ public void test154EnableAccount() throws Exception { @Test public void test155SearchDisabledAccounts() throws Exception { - final String TEST_NAME = "test155SearchDisabledAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1542,10 +1486,8 @@ public void test155SearchDisabledAccounts() throws Exception { @Test public void test156SetValidFrom() throws Exception { - final String TEST_NAME = "test156SetValidFrom"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1586,10 +1528,8 @@ public void test156SetValidFrom() throws Exception { @Test public void test157SetValidTo() throws Exception { - final String TEST_NAME = "test157SetValidTo"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1633,10 +1573,8 @@ public void test157SetValidTo() throws Exception { @Test public void test158DeleteValidToValidFrom() throws Exception { - final String TEST_NAME = "test158DeleteValidToValidFrom"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1688,10 +1626,8 @@ public void test158DeleteValidToValidFrom() throws Exception { @Test public void test159GetLockedoutAccount() throws Exception { - final String TEST_NAME = "test159GetLockedoutAccount"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); DummyAccount dummyAccount = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); dummyAccount.setLockout(true); @@ -1730,10 +1666,8 @@ public void test159GetLockedoutAccount() throws Exception { @Test public void test160SearchLockedAccounts() throws Exception { - final String TEST_NAME = "test160SearchLockedAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1762,10 +1696,8 @@ public void test160SearchLockedAccounts() throws Exception { @Test public void test162UnlockAccount() throws Exception { - final String TEST_NAME = "test162UnlockAccount"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ShadowType accountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, task, @@ -1807,10 +1739,8 @@ public void test162UnlockAccount() throws Exception { @Test public void test163GetAccount() throws Exception { - final String TEST_NAME = "test163GetAccount"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); @@ -1847,10 +1777,8 @@ public void test163GetAccount() throws Exception { @Test public void test163SearchLockedAccounts() throws Exception { - final String TEST_NAME = "test163SearchLockedAccounts"; // GIVEN - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), prismContext); @@ -1876,7 +1804,7 @@ public void test163SearchLockedAccounts() throws Exception { @Test public void test170SearchNull() throws Exception { - testSeachIterative(null, null, true, true, false, + testSearchIterative(null, null, true, true, false, "meathook", "daemon", transformNameFromResource("morgan"), transformNameFromResource("Will")); } @@ -1939,10 +1867,9 @@ SchemaConstants.ICFS_NAME, getWillRepoIcfName(), null, true, @Test public void test180SearchNullPagingOffset0Size3() throws Exception { - final String TEST_NAME = "test180SearchNullPagingSize5"; ObjectPaging paging = prismContext.queryFactory().createPaging(0, 3); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18x(0, 3)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @@ -1953,30 +1880,27 @@ public void test180SearchNullPagingOffset0Size3() throws Exception { */ @Test public void test181SearchNullPagingOffset0Size3Desc() throws Exception { - final String TEST_NAME = "test181SearchNullPagingOffset0Size3Desc"; ObjectPaging paging = prismContext.queryFactory().createPaging(0, 3); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME, OrderDirection.DESCENDING)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18xDesc(0, 3)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @Test public void test182SearchNullPagingOffset1Size2() throws Exception { - final String TEST_NAME = "test182SearchNullPagingOffset1Size2"; ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18x(1, 2)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @Test public void test183SearchNullPagingOffset2Size3Desc() throws Exception { - final String TEST_NAME = "test183SearchNullPagingOffset1Size3Desc"; ObjectPaging paging = prismContext.queryFactory().createPaging(2, 3); paging.setOrdering(createAttributeOrdering(SchemaConstants.ICFS_NAME, OrderDirection.DESCENDING)); - SearchResultMetadata searchMetadata = testSeachIterativePaging(TEST_NAME, null, paging, null, + SearchResultMetadata searchMetadata = testSeachIterativePaging(null, paging, null, getSortedUsernames18xDesc(2, 3)); assertApproxNumberOfAllResults(searchMetadata, getTest18xApproxNumberOfSearchResults()); } @@ -2040,7 +1964,7 @@ public void test197SearchIcfNameAndUidExactNoFetch() throws Exception { @Test public void test198SearchNone() throws Exception { ObjectFilter attrFilter = FilterCreationUtil.createNone(prismContext); - testSeachIterative(attrFilter, null, true, true, false); + testSearchIterative(attrFilter, null, true, true, false); } /** @@ -2050,10 +1974,8 @@ public void test198SearchNone() throws Exception { */ @Test public void test199SearchOnAndOffResource() throws Exception { - final String TEST_NAME = "test199SearchOnAndOffResource"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = createOnOffQuery(); @@ -2091,10 +2013,8 @@ public boolean handle(PrismObject object, OperationResult parentResu */ @Test public void test196SearchOnAndOffResourceNoFetch() throws Exception { - final String TEST_NAME = "test196SearchOnAndOffResourceNoFetch"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); ObjectQuery query = createOnOffQuery(); @@ -2148,7 +2068,7 @@ protected void testSeachIterativeSingleAttrFilter(QName attrQName, T attrVal ObjectFilter filter = prismContext.queryFor(ShadowType.class) .itemWithDef(attrDef, ShadowType.F_ATTRIBUTES, attrDef.getItemName()).eq(attrVal) .buildFilter(); - testSeachIterative(filter, rootOptions, fullShadow, true, false, expectedAccountNames); + testSearchIterative(filter, rootOptions, fullShadow, true, false, expectedAccountNames); } protected void testSeachIterativeAlternativeAttrFilter(QName attr1QName, T attr1Val, @@ -2162,10 +2082,10 @@ protected void testSeachIterativeAlternativeAttrFilter(QName attr1QName, T a .itemWithDef(attr1Def, ShadowType.F_ATTRIBUTES, attr1Def.getItemName()).eq(attr1Val) .or().itemWithDef(attr2Def, ShadowType.F_ATTRIBUTES, attr2Def.getItemName()).eq(attr2Val) .buildFilter(); - testSeachIterative(filter, rootOptions, fullShadow, false, true, expectedAccountNames); + testSearchIterative(filter, rootOptions, fullShadow, false, true, expectedAccountNames); } - private SearchResultMetadata testSeachIterative( + private SearchResultMetadata testSearchIterative( ObjectFilter attrFilter, GetOperationOptions rootOptions, final boolean fullShadow, boolean useObjectClassFilter, final boolean useRepo, String... expectedAccountNames) throws Exception { @@ -2188,8 +2108,6 @@ private SearchResultMetadata testSeachIterative( display("Query", query); - final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - final List> foundObjects = new ArrayList<>(); ResultHandler handler = new ResultHandler() { @@ -2197,8 +2115,6 @@ private SearchResultMetadata testSeachIterative( public boolean handle(PrismObject shadow, OperationResult parentResult) { foundObjects.add(shadow); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - assertTrue(shadow.canRepresent(ShadowType.class)); if (!useRepo) { try { @@ -2254,9 +2170,10 @@ public boolean handle(PrismObject shadow, OperationResult parentResu // This has to be a different method than ordinary search. We care about ordering here. // Also, paged search without sorting does not make much sense anyway. - private SearchResultMetadata testSeachIterativePaging(final String TEST_NAME, ObjectFilter attrFilter, ObjectPaging paging, GetOperationOptions rootOptions, String... expectedAccountNames) throws Exception { - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + private SearchResultMetadata testSeachIterativePaging(ObjectFilter attrFilter, + ObjectPaging paging, GetOperationOptions rootOptions, String... expectedAccountNames) + throws Exception { + OperationResult result = createOperationResult(); ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(RESOURCE_DUMMY_OID, new QName(ResourceTypeUtil.getResourceNamespace(resourceType), SchemaConstants.ACCOUNT_OBJECT_CLASS_LOCAL_NAME), prismContext); @@ -2268,8 +2185,6 @@ private SearchResultMetadata testSeachIterativePaging(final String TEST_NAME, Ob display("Query", query); - final XMLGregorianCalendar startTs = clock.currentTimeXMLGregorianCalendar(); - final List> foundObjects = new ArrayList<>(); ResultHandler handler = new ResultHandler() { @@ -2277,8 +2192,6 @@ private SearchResultMetadata testSeachIterativePaging(final String TEST_NAME, Ob public boolean handle(PrismObject shadow, OperationResult parentResult) { foundObjects.add(shadow); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - assertTrue(shadow.canRepresent(ShadowType.class)); try { checkAccountShadow(shadow, parentResult, true); @@ -2321,9 +2234,8 @@ public boolean handle(PrismObject shadow, OperationResult parentResu @Test public void test200AddGroup() throws Exception { - final String TEST_NAME = "test200AddGroup"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -2383,10 +2295,8 @@ public void test200AddGroup() throws Exception { @Test public void test202GetGroup() throws Exception { - final String TEST_NAME = "test202GetGroup"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2425,10 +2335,8 @@ private void checkGroupPirates(PrismObject shadow, OperationResult r @Test public void test203GetGroupNoFetch() throws Exception { - final String TEST_NAME = "test203GetGroupNoFetch"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); GetOperationOptions rootOptions = new GetOperationOptions(); rootOptions.setNoFetch(true); @@ -2459,10 +2367,7 @@ public void test203GetGroupNoFetch() throws Exception { @Test public void test205ModifyGroupReplace() throws Exception { - final String TEST_NAME = "test205ModifyGroupReplace"; - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2498,9 +2403,8 @@ public void test205ModifyGroupReplace() throws Exception { @Test public void test210AddPrivilege() throws Exception { - final String TEST_NAME = "test210AddPrivilege"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -2551,10 +2455,8 @@ public void test210AddPrivilege() throws Exception { @Test public void test212GetPriv() throws Exception { - final String TEST_NAME = "test212GetPriv"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN PrismObject shadow = provisioningService.getObject(ShadowType.class, PRIVILEGE_PILLAGE_OID, null, null, result); @@ -2589,9 +2491,8 @@ private void checkPrivPillage(PrismObject shadow, OperationResult re @Test public void test214AddPrivilegeBargain() throws Exception { - final String TEST_NAME = "test214AddPrivilegeBargain"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -2659,9 +2560,7 @@ private void checkPrivBargain(PrismObject shadow, OperationResult re @Test public void test220EntitleAccountWillPirates() throws Exception { - final String TEST_NAME = "test220EntitleAccountWillPirates"; - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2704,10 +2603,7 @@ public void test220EntitleAccountWillPirates() throws Exception { */ @Test public void test221GetPirateWill() throws Exception { - final String TEST_NAME = "test221GetPirateWill"; - - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberDummyResourceGroupMembersReadCount(null); @@ -2736,8 +2632,6 @@ public void test221GetPirateWill() throws Exception { @Test public void test222EntitleAccountWillPillage() throws Exception { - final String TEST_NAME = "test222EntitleAccountWillPillage"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2791,8 +2685,6 @@ public void test222EntitleAccountWillPillage() throws Exception { @Test public void test223EntitleAccountWillBargain() throws Exception { - final String TEST_NAME = "test223EntitleAccountWillBargain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3014,8 +2906,6 @@ public void test226WillNonsensePrivilege() throws Exception { @Test public void test230DetitleAccountWillPirates() throws Exception { - final String TEST_NAME = "test230DetitleAccountWillPirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3046,8 +2936,6 @@ public void test230DetitleAccountWillPirates() throws Exception { */ @Test public void test232EntitleAccountWillPiratesIdentifiersName() throws Exception { - final String TEST_NAME = "test232EntitleAccountWillPiratesIdentifiersName"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3078,8 +2966,6 @@ public void test232EntitleAccountWillPiratesIdentifiersName() throws Exception { */ @Test public void test233DetitleAccountWillPiratesIdentifiersName() throws Exception { - final String TEST_NAME = "test233DetitleAccountWillPiratesIdentifiersName"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3110,8 +2996,6 @@ public void test233DetitleAccountWillPiratesIdentifiersName() throws Exception { */ @Test public void test234EntitleAccountWillPiratesIdentifiersUid() throws Exception { - final String TEST_NAME = "test234EntitleAccountWillPiratesIdentifiersUid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3142,8 +3026,6 @@ public void test234EntitleAccountWillPiratesIdentifiersUid() throws Exception { */ @Test public void test235DetitleAccountWillPiratesIdentifiersUid() throws Exception { - final String TEST_NAME = "test235DetitleAccountWillPiratesIdentifiersUid"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3542,8 +3424,6 @@ public void test299DeleteGroupPirates() throws Exception { @Test public void test300AccountRename() throws Exception { - final String TEST_NAME = "test300AccountRename"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3595,8 +3475,6 @@ public void test300AccountRename() throws Exception { */ @Test public void test310ModifyMorganEnlistTimestamp() throws Exception { - final String TEST_NAME = "test310ModifyMorganEnlistTimestamp"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3635,8 +3513,6 @@ public void test310ModifyMorganEnlistTimestamp() throws Exception { */ @Test public void test330ModifyAccountWillPasswordSelfService() throws Exception { - final String TEST_NAME = "test330ModifyAccountWillPasswordSelfService"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3685,8 +3561,6 @@ public void test330ModifyAccountWillPasswordSelfService() throws Exception { */ @Test public void test340ModifyWillReplaceGossipBloodAvast() throws Exception { - final String TEST_NAME = "test340ModifyWillReplaceGossipBloodAvast"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3717,8 +3591,6 @@ public void test340ModifyWillReplaceGossipBloodAvast() throws Exception { */ @Test public void test342ModifyWillAddGossipEunuch() throws Exception { - final String TEST_NAME = "test342ModifyWillAddGossipEunuch"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3749,8 +3621,6 @@ public void test342ModifyWillAddGossipEunuch() throws Exception { */ @Test public void test344ModifyWillDeleteGossipAvast() throws Exception { - final String TEST_NAME = "test344ModifyWillDeleteGossipAvast"; - Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3822,7 +3692,6 @@ protected String getLastModifierName(String expected) { @Test public void test500AddProtectedAccount() throws Exception { - final String TEST_NAME = "test500AddProtectedAccount"; testAddProtectedAccount(ACCOUNT_DAVIEJONES_USERNAME); } @@ -3890,10 +3759,8 @@ public void test502ModifyProtectedAccountShadowAttributes() throws Exception { */ @Test public void test503ModifyProtectedAccountShadowProperty() throws Exception { - final String TEST_NAME = "test503ModifyProtectedAccountShadowProperty"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -3919,7 +3786,6 @@ public void test503ModifyProtectedAccountShadowProperty() throws Exception { @Test public void test509DeleteProtectedAccountShadow() throws Exception { - final String TEST_NAME = "test509DeleteProtectedAccountShadow"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -3950,7 +3816,6 @@ public void test509DeleteProtectedAccountShadow() throws Exception { @Test public void test510AddProtectedAccounts() throws Exception { - final String TEST_NAME = "test510AddProtectedAccounts"; // GIVEN testAddProtectedAccount("Xavier"); testAddProtectedAccount("Xenophobia"); @@ -4034,7 +3899,6 @@ private void testAddAccount(String username) throws Exception { */ @Test public void test520MigrationPrimaryIdentifierValueRefresh() throws Exception { - final String TEST_NAME = "test520MigrationPrimaryIdentifierValueRefresh"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -4066,10 +3930,9 @@ public void test520MigrationPrimaryIdentifierValueRefresh() throws Exception { */ @Test public void test600AddAccountAlreadyExist() throws Exception { - final String TEST_NAME = "test600AddAccountAlreadyExist"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); + OperationResult result = task.getResult(); syncServiceMock.reset(); dummyResourceCtl.addAccount(ACCOUNT_MURRAY_USERNAME, ACCOUNT_MURRAY_USERNAME); @@ -4111,7 +3974,6 @@ public void test600AddAccountAlreadyExist() throws Exception { @Test public void test800LiveSyncInit() throws Exception { - final String TEST_NAME = "test800LiveSyncInit"; syncTokenTask = taskManager.createTaskInstance(TestDummy.class.getName() + ".syncTask"); dummyResource.setSyncStyle(DummySyncStyle.DUMB); @@ -4146,10 +4008,8 @@ public void test800LiveSyncInit() throws Exception { @Test public void test801LiveSyncAddBlackbeard() throws Exception { - final String TEST_NAME = "test801LiveSyncAddBlackbeard"; - // GIVEN - Task task = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -4214,10 +4074,8 @@ public void test801LiveSyncAddBlackbeard() throws Exception { @Test public void test802LiveSyncModifyBlackbeard() throws Exception { - final String TEST_NAME = "test802LiveSyncModifyBlackbeard"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); @@ -4275,108 +4133,107 @@ public void test802LiveSyncModifyBlackbeard() throws Exception { @Test public void test810LiveSyncAddDrakeDumbObjectClass() throws Exception { - testLiveSyncAddDrake("test810LiveSyncAddDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncAddDrake(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test812LiveSyncModifyDrakeDumbObjectClass() throws Exception { - testLiveSyncModifyDrake("test812LiveSyncModifyDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncModifyDrake(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test815LiveSyncAddCorsairsDumbObjectClass() throws Exception { - testLiveSyncAddCorsairs("test815LiveSyncAddCorsairsDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncAddCorsairs(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test817LiveSyncDeleteCorsairsDumbObjectClass() throws Exception { - testLiveSyncDeleteCorsairs("test817LiveSyncDeleteCorsairsDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncDeleteCorsairs(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test819LiveSyncDeleteDrakeDumbObjectClass() throws Exception { - testLiveSyncDeleteDrake("test819LiveSyncDeleteDrakeDumbObjectClass", DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncDeleteDrake(DummySyncStyle.DUMB, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test820LiveSyncAddDrakeSmartObjectClass() throws Exception { - testLiveSyncAddDrake("test820LiveSyncAddDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncAddDrake(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test822LiveSyncModifyDrakeSmartObjectClass() throws Exception { - testLiveSyncModifyDrake("test822LiveSyncModifyDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncModifyDrake(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test825LiveSyncAddCorsairsSmartObjectClass() throws Exception { - testLiveSyncAddCorsairs("test825LiveSyncAddCorsairsDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncAddCorsairs(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test827LiveSyncDeleteCorsairsSmartObjectClass() throws Exception { - testLiveSyncDeleteCorsairs("test827LiveSyncDeleteCorsairsDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); + testLiveSyncDeleteCorsairs(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType), false); } @Test public void test829LiveSyncDeleteDrakeSmartObjectClass() throws Exception { - testLiveSyncDeleteDrake("test829LiveSyncDeleteDrakeDumbObjectClass", DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); + testLiveSyncDeleteDrake(DummySyncStyle.SMART, ProvisioningTestUtil.getDefaultAccountObjectClass(resourceType)); } @Test public void test830LiveSyncAddDrakeDumbAny() throws Exception { - testLiveSyncAddDrake("test830LiveSyncAddDrakeDumbAny", DummySyncStyle.DUMB, null); + testLiveSyncAddDrake(DummySyncStyle.DUMB, null); } @Test public void test832LiveSyncModifyDrakeDumbAny() throws Exception { - testLiveSyncModifyDrake("test832LiveSyncModifyDrakeDumbAny", DummySyncStyle.DUMB, null); + testLiveSyncModifyDrake(DummySyncStyle.DUMB, null); } @Test public void test835LiveSyncAddCorsairsDumbAny() throws Exception { - testLiveSyncAddCorsairs("test835LiveSyncAddCorsairsDumbAny", DummySyncStyle.DUMB, null, true); + testLiveSyncAddCorsairs(DummySyncStyle.DUMB, null, true); } @Test public void test837LiveSyncDeleteCorsairsDumbAny() throws Exception { - testLiveSyncDeleteCorsairs("test837LiveSyncDeleteCorsairsDumbAny", DummySyncStyle.DUMB, null, true); + testLiveSyncDeleteCorsairs(DummySyncStyle.DUMB, null, true); } @Test public void test839LiveSyncDeleteDrakeDumbAny() throws Exception { - testLiveSyncDeleteDrake("test839LiveSyncDeleteDrakeDumbAny", DummySyncStyle.DUMB, null); + testLiveSyncDeleteDrake(DummySyncStyle.DUMB, null); } @Test public void test840LiveSyncAddDrakeSmartAny() throws Exception { - testLiveSyncAddDrake("test840LiveSyncAddDrakeSmartAny", DummySyncStyle.SMART, null); + testLiveSyncAddDrake(DummySyncStyle.SMART, null); } @Test public void test842LiveSyncModifyDrakeSmartAny() throws Exception { - testLiveSyncModifyDrake("test842LiveSyncModifyDrakeSmartAny", DummySyncStyle.SMART, null); + testLiveSyncModifyDrake(DummySyncStyle.SMART, null); } @Test public void test845LiveSyncAddCorsairsSmartAny() throws Exception { - testLiveSyncAddCorsairs("test845LiveSyncAddCorsairsSmartAny", DummySyncStyle.SMART, null, true); + testLiveSyncAddCorsairs(DummySyncStyle.SMART, null, true); } @Test public void test847LiveSyncDeleteCorsairsSmartAny() throws Exception { - testLiveSyncDeleteCorsairs("test847LiveSyncDeleteCorsairsSmartAny", DummySyncStyle.SMART, null, true); + testLiveSyncDeleteCorsairs(DummySyncStyle.SMART, null, true); } @Test public void test849LiveSyncDeleteDrakeSmartAny() throws Exception { - testLiveSyncDeleteDrake("test849LiveSyncDeleteDrakeSmartAny", DummySyncStyle.SMART, null); + testLiveSyncDeleteDrake(DummySyncStyle.SMART, null); } - public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { + public void testLiveSyncAddDrake(DummySyncStyle syncStyle, QName objectClass) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4449,10 +4306,9 @@ public void testLiveSyncAddDrake(final String TEST_NAME, DummySyncStyle syncStyl assertSteadyResource(); } - public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { + public void testLiveSyncModifyDrake(DummySyncStyle syncStyle, QName objectClass) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4506,10 +4362,10 @@ public void testLiveSyncModifyDrake(final String TEST_NAME, DummySyncStyle syncS assertSteadyResource(); } - public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { + public void testLiveSyncAddCorsairs( + DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4581,10 +4437,10 @@ public void testLiveSyncAddCorsairs(final String TEST_NAME, DummySyncStyle syncS assertSteadyResource(); } - public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { + public void testLiveSyncDeleteCorsairs( + DummySyncStyle syncStyle, QName objectClass, boolean expectReaction) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4647,10 +4503,10 @@ public void testLiveSyncDeleteCorsairs(final String TEST_NAME, DummySyncStyle sy assertSteadyResource(); } - public void testLiveSyncDeleteDrake(final String TEST_NAME, DummySyncStyle syncStyle, QName objectClass) throws Exception { + private void testLiveSyncDeleteDrake( + DummySyncStyle syncStyle, QName objectClass) throws Exception { // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); syncServiceMock.reset(); dummyResource.setSyncStyle(syncStyle); @@ -4707,9 +4563,8 @@ public void testLiveSyncDeleteDrake(final String TEST_NAME, DummySyncStyle syncS @Test public void test890LiveSyncModifyProtectedAccount() throws Exception { - final String TEST_NAME = "test890LiveSyncModifyProtectedAccount"; // GIVEN - Task syncTask = taskManager.createTaskInstance(TestDummy.class.getName() + "." + TEST_NAME); + Task syncTask = getTestTask(); OperationResult result = syncTask.getResult(); syncServiceMock.reset(); @@ -4741,10 +4596,8 @@ public void test890LiveSyncModifyProtectedAccount() throws Exception { @Test public void test901FailResourceNotFound() throws Exception { - final String TEST_NAME = "test901FailResourceNotFound"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN try { diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java index 7d1a9fc67c0..76fadf84594 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyCaching.java @@ -6,15 +6,11 @@ */ package com.evolveum.midpoint.provisioning.impl.dummy; -import static org.testng.AssertJUnit.assertTrue; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.Collection; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; import org.springframework.test.annotation.DirtiesContext; @@ -41,22 +37,13 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CachingMetadataType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsStorageTypeType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; /** * Almost the same as TestDummy but this is using a caching configuration. * * @author Radovan Semancik - * */ @ContextConfiguration(locations = "classpath:ctx-provisioning-test-main.xml") @DirtiesContext @@ -94,9 +81,8 @@ protected ItemComparisonResult getExpectedPasswordComparisonResultMismatch() { @Test @Override public void test107AGetModifiedAccountFromCacheMax() throws Exception { - final String TEST_NAME = "test107AGetModifiedAccountFromCacheMax"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -122,8 +108,6 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); @@ -161,9 +145,8 @@ public void test107AGetModifiedAccountFromCacheMax() throws Exception { @Test @Override public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception { - final String TEST_NAME = "test107BGetModifiedAccountFromCacheHighStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -186,8 +169,6 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 0); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); @@ -222,9 +203,8 @@ public void test107BGetModifiedAccountFromCacheHighStaleness() throws Exception */ @Test public void test107CSkipCachingForIncompleteAttributes() throws Exception { - final String TEST_NAME = "test107CSkipCachingForIncompleteAttributes"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); DummyAccount accountWill = getDummyAccountAssert(transformNameFromResource(ACCOUNT_WILL_USERNAME), willIcfUid); @@ -248,8 +228,6 @@ public void test107CSkipCachingForIncompleteAttributes() throws Exception { assertCounterIncrement(InternalCounters.SHADOW_FETCH_OPERATION_COUNT, 1); - XMLGregorianCalendar endTs = clock.currentTimeXMLGregorianCalendar(); - display("Retrieved account shadow", shadow); assertNotNull("No dummy account", shadow); @@ -294,10 +272,8 @@ public void test107CSkipCachingForIncompleteAttributes() throws Exception { @Test @Override public void test119SearchAllAccountsMaxStaleness() throws Exception { - final String TEST_NAME = "test119SearchAllAccountsMaxStaleness"; // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectQuery query = IntegrationTestTools.createAllShadowsQuery(resourceType, SchemaTestConstants.ICF_ACCOUNT_OBJECT_CLASS_LOCAL_NAME, prismContext); display("All shadows query", query); @@ -322,13 +298,13 @@ public void test119SearchAllAccountsMaxStaleness() throws Exception { assertFalse("No shadows found", allShadows.isEmpty()); assertEquals("Wrong number of results", 4, allShadows.size()); - for (PrismObject shadow: allShadows) { + for (PrismObject shadow : allShadows) { display("Found shadow", shadow); ShadowType shadowType = shadow.asObjectable(); OperationResultType fetchResult = shadowType.getFetchResult(); if (fetchResult != null) { - display("fetchResult",fetchResult); - assertEquals("Wrong fetch result status in "+shadow, OperationResultStatusType.SUCCESS, fetchResult.getStatus()); + display("fetchResult", fetchResult); + assertEquals("Wrong fetch result status in " + shadow, OperationResultStatusType.SUCCESS, fetchResult.getStatus()); } assertCachingMetadata(shadow, true, null, startTs); @@ -361,25 +337,25 @@ protected void checkRepoAccountShadowWill(PrismObject shadowRepo, XM @Override protected void assertRepoShadowCacheActivation(PrismObject shadowRepo, ActivationStatusType expectedAdministrativeStatus) { ActivationType activationType = shadowRepo.asObjectable().getActivation(); - assertNotNull("No activation in repo shadow "+shadowRepo, activationType); + assertNotNull("No activation in repo shadow " + shadowRepo, activationType); ActivationStatusType administrativeStatus = activationType.getAdministrativeStatus(); - assertEquals("Wrong activation administrativeStatus in repo shadow "+shadowRepo, expectedAdministrativeStatus, administrativeStatus); + assertEquals("Wrong activation administrativeStatus in repo shadow " + shadowRepo, expectedAdministrativeStatus, administrativeStatus); } @Override protected void assertRepoShadowPasswordValue(PrismObject shadowRepo, PasswordType passwordType, String expectedPassword) throws SchemaException, EncryptionException { ProtectedStringType protectedStringType = passwordType.getValue(); - assertNotNull("No password value in repo shadow "+shadowRepo, protectedStringType); - assertProtectedString("Wrong password value in repo shadow "+shadowRepo, expectedPassword, protectedStringType, CredentialsStorageTypeType.HASHING); + assertNotNull("No password value in repo shadow " + shadowRepo, protectedStringType); + assertProtectedString("Wrong password value in repo shadow " + shadowRepo, expectedPassword, protectedStringType, CredentialsStorageTypeType.HASHING); } @Override protected void assertRepoCachingMetadata(PrismObject shadowFromRepo, XMLGregorianCalendar start, XMLGregorianCalendar end) { CachingMetadataType cachingMetadata = shadowFromRepo.asObjectable().getCachingMetadata(); - assertNotNull("No caching metadata in "+shadowFromRepo, cachingMetadata); + assertNotNull("No caching metadata in " + shadowFromRepo, cachingMetadata); - TestUtil.assertBetween("Wrong retrieval timestamp in caching metadata in "+shadowFromRepo, + TestUtil.assertBetween("Wrong retrieval timestamp in caching metadata in " + shadowFromRepo, start, end, cachingMetadata.getRetrievalTimestamp()); } @@ -387,14 +363,13 @@ protected void assertRepoCachingMetadata(PrismObject shadowFromRepo, protected void assertCachingMetadata(PrismObject shadow, boolean expectedCached, XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) { CachingMetadataType cachingMetadata = shadow.asObjectable().getCachingMetadata(); if (expectedCached) { - assertNotNull("No caching metadata in "+shadow, cachingMetadata); - TestUtil.assertBetween("Wrong retrievalTimestamp in caching metadata in "+shadow, startTs, endTs, cachingMetadata.getRetrievalTimestamp()); + assertNotNull("No caching metadata in " + shadow, cachingMetadata); + TestUtil.assertBetween("Wrong retrievalTimestamp in caching metadata in " + shadow, startTs, endTs, cachingMetadata.getRetrievalTimestamp()); } else { super.assertCachingMetadata(shadow, expectedCached, startTs, endTs); } } - @Override protected void checkRepoAccountShadow(PrismObject repoShadow) { ProvisioningTestUtil.checkRepoShadow(repoShadow, ShadowKindType.ACCOUNT, null); @@ -406,10 +381,10 @@ protected void checkRepoEntitlementShadow(PrismObject repoShadow) { } @Override - protected void assertRepoShadowAttributes(Collection> attributes, int expectedNumberOfIdentifiers) { + protected void assertRepoShadowAttributes(Collection> attributes, int expectedNumberOfIdentifiers) { // We can only assert that there are at least the identifiers. But we do not know how many attributes should be there - assertTrue("Unexpected number of attributes in repo shadow, expected at least "+ - expectedNumberOfIdentifiers+", but was "+attributes.size(), attributes.size() >= expectedNumberOfIdentifiers); + assertTrue("Unexpected number of attributes in repo shadow, expected at least " + + expectedNumberOfIdentifiers + ", but was " + attributes.size(), attributes.size() >= expectedNumberOfIdentifiers); } @Override @@ -418,13 +393,15 @@ protected void assertSyncOldShadow(PrismObject oldShadow, } @Override - protected void assertRepoShadowCachedAttributeValue(PrismObject shadowRepo, String attrName, T... attrValues) { + protected void assertRepoShadowCachedAttributeValue( + PrismObject shadowRepo, String attrName, T... attrValues) { assertAttribute(shadowRepo, attrName, attrValues); } @Override - protected void checkCachedAccountShadow(PrismObject shadow, OperationResult parentResult, boolean fullShadow, XMLGregorianCalendar startTs, - XMLGregorianCalendar endTs) throws SchemaException { + protected void checkCachedAccountShadow( + PrismObject shadow, OperationResult parentResult, boolean fullShadow, + XMLGregorianCalendar startTs, XMLGregorianCalendar endTs) throws SchemaException { super.checkAccountShadow(shadow, parentResult, fullShadow); if (fullShadow) { assertCachingMetadata(shadow, true, startTs, endTs); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java index 60e2e3e4daf..276c7a11652 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyExtra.java @@ -90,7 +90,7 @@ protected void assertSchemaSanity(ResourceSchema resourceSchema, ResourceType re Collection associationDefinitions = accountRDef.getAssociationDefinitions(); assertEquals("Wrong number of association defs", 3, associationDefinitions.size()); RefinedAssociationDefinition crewAssociationDef = accountRDef.findAssociationDefinition(ASSOCIATION_CREW_NAME); - assertNotNull("No definitin for crew assocation", crewAssociationDef); + assertNotNull("No definition for crew association", crewAssociationDef); } @Override @@ -104,7 +104,6 @@ protected void assertNativeCredentialsCapability(CredentialsCapabilityType capCr @Test public void test400AddAccountElizabeth() throws Exception { - final String TEST_NAME = "test400AddAccountElizabeth"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -115,8 +114,6 @@ public void test400AddAccountElizabeth() throws Exception { display("Adding shadow", account); - XMLGregorianCalendar start = clock.currentTimeXMLGregorianCalendar(); - // WHEN when(); String addedObjectOid = provisioningService.addObject(account, null, null, task, result); @@ -125,8 +122,6 @@ public void test400AddAccountElizabeth() throws Exception { then(); assertSuccess(result); - XMLGregorianCalendar end = clock.currentTimeXMLGregorianCalendar(); - assertEquals(ACCOUNT_ELIZABETH_OID, addedObjectOid); account.checkConsistence(); @@ -136,8 +131,6 @@ public void test400AddAccountElizabeth() throws Exception { PrismObject accountProvisioning = provisioningService.getObject(ShadowType.class, ACCOUNT_ELIZABETH_OID, null, task, result); - XMLGregorianCalendar tsAfterRead = clock.currentTimeXMLGregorianCalendar(); - display("Account will from provisioning", accountProvisioning); DummyAccount dummyAccount = getDummyAccountAssert(ACCOUNT_ELIZABETH_USERNAME, ACCOUNT_ELIZABETH_USERNAME); @@ -238,7 +231,6 @@ public void test419DisassociateCrewWillElizabeth() throws Exception { @Test public void test499DeleteAccountElizabeth() throws Exception { - final String TEST_NAME = "test499DeleteAccountElizabeth"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java index 5aace10768e..5c4f77679b5 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyNegative.java @@ -98,7 +98,6 @@ public void testGetResourceBrokenSchema(BreakMode breakMode) throws Exception { @Test public void test190GetResource() throws Exception { - final String TEST_NAME = "test190GetResource"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -119,7 +118,6 @@ public void test190GetResource() throws Exception { @Test public void test200AddAccountNullAttributes() throws Exception { - final String TEST_NAME = "test200AddAccountNullAttributes"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -175,7 +173,7 @@ public void test201AddAccountEmptyAttributes() throws Exception { } @Test - public void test210AddAccountNoObjectclass() throws Exception { + public void test210AddAccountNoObjectClass() throws Exception { // GIVEN Task task =getTestTask(); OperationResult result = getTestOperationResult(); @@ -206,10 +204,8 @@ public void test210AddAccountNoObjectclass() throws Exception { @Test public void test220AddAccountNoResourceRef() throws Exception { - final String TEST_NAME = "test220AddAccountNoResourceRef"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -231,16 +227,14 @@ public void test220AddAccountNoResourceRef() throws Exception { display("Expected exception", e); } - //FIXME: not sure, if this check is needed..if the reosurce is not specified, provisioning probably will be not called. + //FIXME: not sure, if this check is needed..if the resource is not specified, provisioning probably will be not called. // syncServiceMock.assertNotifyFailureOnly(); } @Test public void test221DeleteAccountResourceNotFound() throws Exception { - final String TEST_NAME = "test221DeleteAccountResourceNotFound"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); syncServiceMock.reset(); @@ -273,10 +267,8 @@ public void test221DeleteAccountResourceNotFound() throws Exception { */ @Test public void test230GetAccountDeletedShadow() throws Exception { - final String TEST_NAME = "test230GetAccountDeletedShadow"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyNegative.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject account = PrismTestUtil.parseObject(ACCOUNT_MORGAN_FILE); @@ -285,7 +277,7 @@ public void test230GetAccountDeletedShadow() throws Exception { repositoryService.deleteObject(ShadowType.class, shadowOid, result); // reset - task = taskManager.createTaskInstance(TestDummyNegative.class.getName() + "." + TEST_NAME); + task = createPlainTask(); result = task.getResult(); syncServiceMock.reset(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java index 605b7e58cbf..f06eeb893fb 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyResourceAndSchemaCaching.java @@ -11,8 +11,6 @@ import java.util.ArrayList; import java.util.Collection; -import com.evolveum.midpoint.prism.delta.*; -import com.evolveum.midpoint.prism.path.ItemPath; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.testng.AssertJUnit; @@ -21,6 +19,10 @@ import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; import com.evolveum.midpoint.prism.PrismObject; +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.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; @@ -33,21 +35,14 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.ProjectionPolicyType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; /** * The test of Provisioning service on the API level. It checks proper caching of resource and schemas. - * + *

* The test is using dummy resource for speed and flexibility. * * @author Radovan Semancik @@ -58,10 +53,8 @@ public class TestDummyResourceAndSchemaCaching extends AbstractDummyTest { @Test public void test010GetResource() throws Exception { - final String TEST_NAME = "test010GetResource"; // GIVEN - OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // Check that there is no schema before test (pre-condition) PrismObject resourceBefore = repositoryService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, result); @@ -127,10 +120,8 @@ public void test010GetResource() throws Exception { @Test public void test011GetResourceAgain() throws Exception { - final String TEST_NAME = "test011GetResourceAgain"; // GIVEN - OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN PrismObject resourceProvisioning = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_OID, null, null, result); @@ -197,10 +188,8 @@ public void test011GetResourceAgain() throws Exception { */ @Test public void test012AddAccountGetResource() throws Exception { - final String TEST_NAME = "test012AddAccountGetResource"; // GIVEN - OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN addAccount(ACCOUNT_WILL_FILE); @@ -239,10 +228,8 @@ public void test012AddAccountGetResource() throws Exception { @Test public void test013GetResourceNoFetch() throws Exception { - final String TEST_NAME = "test013GetResourceNoFetch"; // GIVEN - OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); Collection> options = GetOperationOptions.createNoFetchCollection(); @@ -305,17 +292,14 @@ public void test013GetResourceNoFetch() throws Exception { assertConnectorInstanceUnchanged(resourceProvisioning); } - /** * Change something that is not important. The cached resource should be refreshed, the schema re-parsed * but the connector should still be cached. */ @Test public void test020ModifyAndGetResource() throws Exception { - final String TEST_NAME = "test020ModifyAndGetResource"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Change something that's not that important @@ -324,7 +308,7 @@ public void test020ModifyAndGetResource() throws Exception { ObjectDelta objectDelta = prismContext.deltaFactory().object() .createModificationReplaceContainer(ResourceType.class, RESOURCE_DUMMY_OID, - ResourceType.F_PROJECTION, projectionPolicyType); + ResourceType.F_PROJECTION, projectionPolicyType); // WHEN provisioningService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, objectDelta.getModifications(), null, null, task, result); @@ -373,10 +357,8 @@ public void test020ModifyAndGetResource() throws Exception { */ @Test public void test022GetAccountGetResource() throws Exception { - final String TEST_NAME = "test012AddAccountGetResource"; // GIVEN - OperationResult result = new OperationResult(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN getAccount(ACCOUNT_WILL_OID); @@ -417,16 +399,14 @@ public void test022GetAccountGetResource() throws Exception { /** * Change resource directly in repo. This simulates the change done by other node. The connector cache should * be refreshed. - * + *

* Change something that is not important. The cached resource should be refreshed, the schema re-parsed * but the connector should still be cached. */ @Test public void test023ModifyRepoAndGetResource() throws Exception { - final String TEST_NAME = "test023ModifyRepoAndGetResource"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Change something that's not that important @@ -435,7 +415,7 @@ public void test023ModifyRepoAndGetResource() throws Exception { ObjectDelta objectDelta = prismContext.deltaFactory().object() .createModificationReplaceContainer(ResourceType.class, RESOURCE_DUMMY_OID, - ResourceType.F_PROJECTION, projectionPolicyType); + ResourceType.F_PROJECTION, projectionPolicyType); // WHEN repositoryService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, objectDelta.getModifications(), result); @@ -484,17 +464,15 @@ public void test023ModifyRepoAndGetResource() throws Exception { */ @Test public void test030ModifyConnectorConfigAndGetResource() throws Exception { - final String TEST_NAME = "test030ModifyConnectorConfigAndGetResource"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Change part of connector configuration. We change quite a useless part. But midPoint does not know that // it is useless and need to re-initialize the connector Collection modifications = new ArrayList<>(1); PropertyDelta uselessStringDelta = createUselessStringDelta("patlama chamalalija paprtala"); - ((Collection)modifications).add(uselessStringDelta); + ((Collection) modifications).add(uselessStringDelta); // WHEN provisioningService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, modifications, null, null, task, result); @@ -508,23 +486,21 @@ public void test030ModifyConnectorConfigAndGetResource() throws Exception { /** * Change part of connector configuration. Change it directly in repo to simulate change * from another midPoint node. - * + *

* The cached resource should be refreshed, the schema re-parsed. * The connector also needs to re-initialized. */ @Test public void test031ModifyConnectorConfigRepoAndGetResource() throws Exception { - final String TEST_NAME = "test031ModifyConnectorConfigRepoAndGetResource"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // Change part of connector configuration. We change quite a useless part. But midPoint does not know that // it is useless and need to re-initialize the connector Collection modifications = new ArrayList<>(1); PropertyDelta uselessStringDelta = createUselessStringDelta("Rudolfovo Tajemstvi"); - ((Collection)modifications).add(uselessStringDelta); + ((Collection) modifications).add(uselessStringDelta); // WHEN repositoryService.modifyObject(ResourceType.class, RESOURCE_DUMMY_OID, modifications, result); @@ -538,10 +514,8 @@ public void test031ModifyConnectorConfigRepoAndGetResource() throws Exception { @Test public void test900DeleteResource() throws Exception { - final String TEST_NAME = "test900DeleteResource"; // GIVEN - Task task = taskManager.createTaskInstance(TestDummyResourceAndSchemaCaching.class.getName() - + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -653,5 +627,4 @@ private PrismObject getAccount(String oid) throws ObjectNotFoundExce TestUtil.assertSuccess(result); return account; } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java index 228422bf1bb..a21c32305e7 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummySchemaless.java @@ -6,16 +6,11 @@ */ package com.evolveum.midpoint.provisioning.impl.dummy; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.Collection; import java.util.List; - import javax.xml.namespace.QName; import org.apache.commons.lang.StringUtils; @@ -62,19 +57,8 @@ import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CachingMetadataType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilitiesType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CapabilityCollectionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.XmlSchemaType; -import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ActivationCapabilityType; -import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.CredentialsCapabilityType; -import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ReadCapabilityType; -import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.ScriptCapabilityType; -import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.TestConnectionCapabilityType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.*; /** * The test of Provisioning service on the API level. The test is using dummy @@ -169,10 +153,9 @@ public void test000Integrity() throws Exception { IntegrationTestTools.assertConnectorSchemaSanity(connector, prismContext); } - /** * This should be the very first test that works with the resource. - * + *

* The original repository object does not have resource schema. The schema * should be generated from the resource on the first use. This is the test * that executes testResource and checks whether the schema was generated. @@ -334,14 +317,13 @@ public void resourceStaticSchemaTest(int expectedConnectorInitCount) throws Exce * MID-4472, MID-4174 */ @Test - public void test030ResourceStatciSchemaResourceAndConnectorCaching() throws Exception { - resourceStatciSchemaResourceAndConnectorCaching("test030ResourceStatciSchemaResourceAndConnectorCaching"); + public void test030ResourceStaticSchemaResourceAndConnectorCaching() throws Exception { + resourceStaticSchemaResourceAndConnectorCaching(); } - public void resourceStatciSchemaResourceAndConnectorCaching(final String TEST_NAME) throws Exception { - + private void resourceStaticSchemaResourceAndConnectorCaching() throws Exception { // GIVEN - OperationResult result = new OperationResult(TestOpenDj.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // re-read the resource before tests so we have a clean slate, e.g. configuration properly parsed (no raw elements) resourceStaticSchema = provisioningService.getObject(ResourceType.class, RESOURCE_DUMMY_STATIC_SCHEMA_OID, null, null, result); @@ -407,7 +389,7 @@ public void resourceStatciSchemaResourceAndConnectorCaching(final String TEST_NA resourceAgain.asObjectable().setFetchResult(null); ObjectDelta dummyResourceDiff = DiffUtil.diff(resourceStaticSchema, resourceAgain); display("Dummy resource diff", dummyResourceDiff); - assertTrue("The resource read again is not the same as the original. diff:"+dummyResourceDiff, dummyResourceDiff.isEmpty()); + assertTrue("The resource read again is not the same as the original. diff:" + dummyResourceDiff, dummyResourceDiff.isEmpty()); // Now we stick our nose deep inside the provisioning impl. But we need // to make sure that the @@ -436,7 +418,6 @@ public void resourceStatciSchemaResourceAndConnectorCaching(final String TEST_NA @Test public void test040ReAddResourceStaticSchema() throws Exception { - final String TEST_NAME = "test040ReAddResourceStaticSchema"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -476,14 +457,13 @@ public void test042ResourceStaticSchemaTestAgain() throws Exception { * MID-4472, MID-4174 */ @Test - public void test044ResourceStatciSchemaResourceAndConnectorCachingAgain() throws Exception { - resourceStatciSchemaResourceAndConnectorCaching("test044ResourceStatciSchemaResourceAndConnectorCachingAgain"); + public void test044ResourceStaticSchemaResourceAndConnectorCachingAgain() throws Exception { + resourceStaticSchemaResourceAndConnectorCaching(); } - /** * This should be the very first test that works with the resource. - * + *

* The original repository object does not have resource schema. The schema * should be generated from the resource on the first use. This is the test * that executes testResource and checks whether the schema was generated. @@ -565,12 +545,12 @@ public void test106GetObjectStaticSchema() throws Exception { private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { ResourceType resourceType = resourceStaticSchema.asObjectable(); - assertNotNull("No resource schema in "+resourceType, resorceSchema); + assertNotNull("No resource schema in " + resourceType, resorceSchema); QName objectClassQname = new QName(ResourceTypeUtil.getResourceNamespace(resourceType), "AccountObjectClass"); ObjectClassComplexTypeDefinition accountDefinition = resorceSchema.findObjectClassDefinition(objectClassQname); - assertNotNull("No object class definition for "+objectClassQname+" in resource schema", accountDefinition); + assertNotNull("No object class definition for " + objectClassQname + " in resource schema", accountDefinition); ObjectClassComplexTypeDefinition accountDef1 = resorceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); - assertTrue("Mismatched account definition: "+accountDefinition+" <-> "+accountDef1, accountDefinition == accountDef1); + assertTrue("Mismatched account definition: " + accountDefinition + " <-> " + accountDef1, accountDefinition == accountDef1); assertNotNull("No object class definition " + objectClassQname, accountDefinition); assertEquals("Object class " + objectClassQname + " is not account", ShadowKindType.ACCOUNT, accountDefinition.getKind()); @@ -582,24 +562,23 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertNotNull("Null identifiers for " + objectClassQname, identifiers); assertFalse("Empty identifiers for " + objectClassQname, identifiers.isEmpty()); - ResourceAttributeDefinition uidAttributeDefinition = accountDefinition.findAttributeDefinition(SchemaTestConstants.ICFS_UID); - assertNotNull("No definition for attribute "+SchemaTestConstants.ICFS_UID, uidAttributeDefinition); - assertTrue("Attribute "+SchemaTestConstants.ICFS_UID+" in not an identifier",uidAttributeDefinition.isPrimaryIdentifier(accountDefinition)); - assertTrue("Attribute "+SchemaTestConstants.ICFS_UID+" in not in identifiers list",identifiers.contains(uidAttributeDefinition)); - assertEquals("Wrong displayName for attribute "+SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidAttributeDefinition.getDisplayName()); - assertEquals("Wrong displayOrder for attribute "+SchemaTestConstants.ICFS_UID, (Integer)100, uidAttributeDefinition.getDisplayOrder()); + assertNotNull("No definition for attribute " + SchemaTestConstants.ICFS_UID, uidAttributeDefinition); + assertTrue("Attribute " + SchemaTestConstants.ICFS_UID + " in not an identifier", uidAttributeDefinition.isPrimaryIdentifier(accountDefinition)); + assertTrue("Attribute " + SchemaTestConstants.ICFS_UID + " in not in identifiers list", identifiers.contains(uidAttributeDefinition)); + assertEquals("Wrong displayName for attribute " + SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidAttributeDefinition.getDisplayName()); + assertEquals("Wrong displayOrder for attribute " + SchemaTestConstants.ICFS_UID, (Integer) 100, uidAttributeDefinition.getDisplayOrder()); Collection secondaryIdentifiers = accountDefinition.getSecondaryIdentifiers(); assertNotNull("Null secondary identifiers for " + objectClassQname, secondaryIdentifiers); assertFalse("Empty secondary identifiers for " + objectClassQname, secondaryIdentifiers.isEmpty()); ResourceAttributeDefinition nameAttributeDefinition = accountDefinition.findAttributeDefinition(SchemaTestConstants.ICFS_NAME); - assertNotNull("No definition for attribute "+SchemaTestConstants.ICFS_NAME, nameAttributeDefinition); - assertTrue("Attribute "+SchemaTestConstants.ICFS_NAME+" in not an identifier",nameAttributeDefinition.isSecondaryIdentifier(accountDefinition)); - assertTrue("Attribute "+SchemaTestConstants.ICFS_NAME+" in not in identifiers list",secondaryIdentifiers.contains(nameAttributeDefinition)); - assertEquals("Wrong displayName for attribute "+SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameAttributeDefinition.getDisplayName()); - assertEquals("Wrong displayOrder for attribute "+SchemaTestConstants.ICFS_NAME, (Integer)110, nameAttributeDefinition.getDisplayOrder()); + assertNotNull("No definition for attribute " + SchemaTestConstants.ICFS_NAME, nameAttributeDefinition); + assertTrue("Attribute " + SchemaTestConstants.ICFS_NAME + " in not an identifier", nameAttributeDefinition.isSecondaryIdentifier(accountDefinition)); + assertTrue("Attribute " + SchemaTestConstants.ICFS_NAME + " in not in identifiers list", secondaryIdentifiers.contains(nameAttributeDefinition)); + assertEquals("Wrong displayName for attribute " + SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameAttributeDefinition.getDisplayName()); + assertEquals("Wrong displayOrder for attribute " + SchemaTestConstants.ICFS_NAME, (Integer) 110, nameAttributeDefinition.getDisplayOrder()); assertNotNull("Null identifiers in account", accountDef1.getPrimaryIdentifiers()); assertFalse("Empty identifiers in account", accountDef1.getPrimaryIdentifiers().isEmpty()); @@ -614,11 +593,11 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertEquals(0, uidDef.getMinOccurs()); assertFalse("No UID display name", StringUtils.isBlank(uidDef.getDisplayName())); assertFalse("UID has create", uidDef.canAdd()); - assertFalse("UID has update",uidDef.canModify()); - assertTrue("No UID read",uidDef.canRead()); + assertFalse("UID has update", uidDef.canModify()); + assertTrue("No UID read", uidDef.canRead()); assertTrue("UID definition not in identifiers", accountDef1.getPrimaryIdentifiers().contains(uidDef)); - assertEquals("Wrong refined displayName for attribute "+SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidDef.getDisplayName()); - assertEquals("Wrong refined displayOrder for attribute "+SchemaTestConstants.ICFS_UID, (Integer)100, uidDef.getDisplayOrder()); + assertEquals("Wrong refined displayName for attribute " + SchemaTestConstants.ICFS_UID, "Modified ConnId UID", uidDef.getDisplayName()); + assertEquals("Wrong refined displayOrder for attribute " + SchemaTestConstants.ICFS_UID, (Integer) 100, uidDef.getDisplayOrder()); ResourceAttributeDefinition nameDef = accountDef1 .findAttributeDefinition(SchemaTestConstants.ICFS_NAME); @@ -626,13 +605,13 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertEquals(1, nameDef.getMinOccurs()); assertFalse("No NAME displayName", StringUtils.isBlank(nameDef.getDisplayName())); assertTrue("No NAME create", nameDef.canAdd()); - assertTrue("No NAME update",nameDef.canModify()); - assertTrue("No NAME read",nameDef.canRead()); + assertTrue("No NAME update", nameDef.canModify()); + assertTrue("No NAME read", nameDef.canRead()); assertTrue("NAME definition not in identifiers", accountDef1.getSecondaryIdentifiers().contains(nameDef)); - assertEquals("Wrong refined displayName for attribute "+SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameDef.getDisplayName()); - assertEquals("Wrong refined displayOrder for attribute "+SchemaTestConstants.ICFS_NAME, (Integer)110, nameDef.getDisplayOrder()); + assertEquals("Wrong refined displayName for attribute " + SchemaTestConstants.ICFS_NAME, "Modified ConnId Name", nameDef.getDisplayName()); + assertEquals("Wrong refined displayOrder for attribute " + SchemaTestConstants.ICFS_NAME, (Integer) 110, nameDef.getDisplayOrder()); - assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef1.findAttributeDefinition(new QName(SchemaTestConstants.NS_ICFS,"password"))); + assertNull("The _PASSSWORD_ attribute sneaked into schema", accountDef1.findAttributeDefinition(new QName(SchemaTestConstants.NS_ICFS, "password"))); // ACCOUNT ObjectClassComplexTypeDefinition accountDef = resorceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); @@ -645,7 +624,7 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertTrue("No fullname create", fullnameDef.canAdd()); assertTrue("No fullname update", fullnameDef.canModify()); assertTrue("No fullname read", fullnameDef.canRead()); - assertTrue("Wrong displayOrder for attribute fullName: "+fullnameDef.getDisplayOrder(), + assertTrue("Wrong displayOrder for attribute fullName: " + fullnameDef.getDisplayOrder(), fullnameDef.getDisplayOrder() == 200 || fullnameDef.getDisplayOrder() == 250 || fullnameDef.getDisplayOrder() == 260); // GROUP @@ -660,21 +639,19 @@ private void assertStaticSchemaSanity(ResourceSchema resorceSchema) { assertTrue("No members update", membersDef.canModify()); assertTrue("No members read", membersDef.canRead()); - assertEquals("Unexpected number of schema definitions in "+dummyResourceSchemalessCtl.getName()+" dummy resource", dummyResourceStaticSchema.getNumberOfObjectclasses(), resorceSchema.getDefinitions().size()); + assertEquals("Unexpected number of schema definitions in " + dummyResourceSchemalessCtl.getName() + " dummy resource", dummyResourceStaticSchema.getNumberOfObjectclasses(), resorceSchema.getDefinitions().size()); - for (Definition def: resorceSchema.getDefinitions()) { + for (Definition def : resorceSchema.getDefinitions()) { if (def instanceof RefinedObjectClassDefinition) { - AssertJUnit.fail("Refined definition sneaked into resource schema of "+dummyResourceSchemalessCtl.getName()+" dummy resource: "+def); + AssertJUnit.fail("Refined definition sneaked into resource schema of " + dummyResourceSchemalessCtl.getName() + " dummy resource: " + def); } } } @Test public void test107Capabilities() throws Exception { - final String TEST_NAME = "test107Capabilities"; - // GIVEN - OperationResult result = new OperationResult(TestDummy.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN when(); @@ -753,19 +730,16 @@ public void test200AddAccount() throws Exception { ShadowType accountType = repositoryService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, result) .asObjectable(); PrismAsserts.assertEqualsPolyString("Wrong name", "will", accountType.getName()); -// assertEquals("will", accountType.getName()); ShadowType provisioningAccountType = provisioningService.getObject(ShadowType.class, ACCOUNT_WILL_OID, null, null, result).asObjectable(); display("account from provisioning", provisioningAccountType); PrismAsserts.assertEqualsPolyString("Wrong name", "will", provisioningAccountType.getName()); -// assertEquals("will", provisioningAccountType.getName()); assertNull("The _PASSSWORD_ attribute sneaked into shadow", ShadowUtil.getAttributeValues( provisioningAccountType, new QName(SchemaConstants.NS_ICF_SCHEMA, "password"))); // Check if the account was created in the dummy resource - DummyAccount dummyAccount = dummyResourceStaticSchema.getAccountByUsername("will"); assertNotNull("No dummy account", dummyAccount); assertEquals("Fullname is wrong", "Will Turner", dummyAccount.getAttributeValue("fullname")); @@ -779,7 +753,5 @@ public void test200AddAccount() throws Exception { display("Repository shadow", shadowFromRepo.debugDump()); ProvisioningTestUtil.checkRepoAccountShadow(shadowFromRepo); - } - } diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java index a475d829cb6..bb6ad792bcf 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/manual/AbstractManualResourceTest.java @@ -332,7 +332,6 @@ public void test006Capabilities() throws Exception { @Test public void test100AddAccountWill() throws Exception { - final String TEST_NAME = "test100AddAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -404,7 +403,6 @@ public void test100AddAccountWill() throws Exception { @Test public void test102GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test102GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -438,7 +436,6 @@ public void test102GetAccountWillFuture() throws Exception { */ @Test public void test104RefreshAccountWill() throws Exception { - final String TEST_NAME = "test104RefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -492,7 +489,6 @@ protected void backingStoreAddWill() throws IOException { @Test public void test106AddToBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test106AddToBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -533,7 +529,6 @@ public void test106AddToBackingStoreAndGetAccountWill() throws Exception { @Test public void test108GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test108GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -576,7 +571,6 @@ public void test108GetAccountWillFuture() throws Exception { @Test public void test109GetAccountWillFutureNoFetch() throws Exception { - final String TEST_NAME = "test109GetAccountWillFutureNoFetch"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -617,7 +611,6 @@ public void test109GetAccountWillFutureNoFetch() throws Exception { */ @Test public void test110CloseCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test110CloseCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -679,7 +672,6 @@ public void test110CloseCaseAndRefreshAccountWill() throws Exception { */ @Test public void test120RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test120RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -731,7 +723,6 @@ public void test120RefreshAccountWillAfter5min() throws Exception { */ @Test public void test130RefreshAccountWillAfter16min() throws Exception { - final String TEST_NAME = "test130RefreshAccountWillAfter16min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -783,7 +774,6 @@ public void test130RefreshAccountWillAfter16min() throws Exception { */ @Test public void test132RefreshAccountWillAfter27min() throws Exception { - final String TEST_NAME = "test132RefreshAccountWillAfter27min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -822,7 +812,6 @@ public void test132RefreshAccountWillAfter27min() throws Exception { @Test public void test200ModifyAccountWillFullname() throws Exception { - final String TEST_NAME = "test200ModifyAccountWillFullname"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -904,7 +893,6 @@ public void test200ModifyAccountWillFullname() throws Exception { @Test public void test202RefreshAccountWill() throws Exception { - final String TEST_NAME = "test202RefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -984,7 +972,6 @@ public void test202RefreshAccountWill() throws Exception { */ @Test public void test204CloseCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test204CloseCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1077,7 +1064,6 @@ public void test204CloseCaseAndRefreshAccountWill() throws Exception { */ @Test public void test210RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test210RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1145,7 +1131,6 @@ protected void backingStoreUpdateWill(String newFullName, ActivationStatusType n @Test public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test212UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1209,7 +1194,6 @@ public void test212UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test220ModifyAccountWillDisable() throws Exception { - final String TEST_NAME = "test220ModifyAccountWillDisable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1292,7 +1276,6 @@ public void test220ModifyAccountWillDisable() throws Exception { */ @Test public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { - final String TEST_NAME = "test230ModifyAccountWillChangePasswordAndEnable"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1382,7 +1365,6 @@ public void test230ModifyAccountWillChangePasswordAndEnable() throws Exception { */ @Test public void test240CloseDisableCaseAndReadAccountWill() throws Exception { - final String TEST_NAME = "test240CloseDisableCaseAndReadAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1493,7 +1475,6 @@ public void test240CloseDisableCaseAndReadAccountWill() throws Exception { */ @Test public void test250RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test250RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1580,7 +1561,6 @@ public void test250RefreshAccountWillAfter5min() throws Exception { @Test public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test252UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1645,7 +1625,6 @@ public void test252UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test260ClosePasswordChangeCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1744,7 +1723,6 @@ public void test260ClosePasswordChangeCaseAndRefreshAccountWill() throws Excepti */ @Test public void test270RefreshAccountWillAfter7min() throws Exception { - final String TEST_NAME = "test270RefreshAccountWillAfter7min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1842,7 +1820,6 @@ public void test270RefreshAccountWillAfter7min() throws Exception { */ @Test public void test271RefreshAccountWillAfter12min() throws Exception { - final String TEST_NAME = "test271RefreshAccountWillAfter12min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1937,7 +1914,6 @@ public void test271RefreshAccountWillAfter12min() throws Exception { @Test public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { - final String TEST_NAME = "test272UpdateBackingStoreAndGetAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2001,7 +1977,6 @@ public void test272UpdateBackingStoreAndGetAccountWill() throws Exception { */ @Test public void test280RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test132RefreshAccountWillAfter10min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2089,7 +2064,6 @@ public void test280RefreshAccountWillAfter5min() throws Exception { */ @Test public void test290RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test134RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2154,7 +2128,6 @@ public void test290RefreshAccountWillAfter5min() throws Exception { @Test public void test300DeleteAccountWill() throws Exception { - final String TEST_NAME = "test300DeleteAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2223,7 +2196,6 @@ public void test300DeleteAccountWill() throws Exception { @Test public void test302GetAccountWillFuture() throws Exception { - final String TEST_NAME = "test302GetAccountWillFuture"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2248,7 +2220,6 @@ public void test302GetAccountWillFuture() throws Exception { @Test public void test303GetAccountWillFutureNoFetch() throws Exception { - final String TEST_NAME = "test303GetAccountWillFutureNoFetch"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2280,7 +2251,6 @@ public void test303GetAccountWillFutureNoFetch() throws Exception { */ @Test public void test310CloseCaseAndRefreshAccountWill() throws Exception { - final String TEST_NAME = "test310CloseCaseAndRefreshAccountWill"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -2346,7 +2316,6 @@ public void test310CloseCaseAndRefreshAccountWill() throws Exception { */ @Test public void test320RefreshAccountWillAfter5min() throws Exception { - final String TEST_NAME = "test320RefreshAccountWillAfter5min"; // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java index 46cc1db8b42..5a9472decfc 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDjDumber.java @@ -67,10 +67,11 @@ protected void assertTimestampType(String attrName, ResourceAttributeDefinition< protected void assertTimestamp(String attrName, Object timestampValue) { if (!(timestampValue instanceof String)) { fail("Wrong type of "+attrName+", expected String but was "+timestampValue.getClass()); + } else { + String str = (String) timestampValue; + assertTrue("Timestamp " + attrName + " does not start with 2: " + str, str.startsWith("2")); + assertTrue("Timestamp " + attrName + " does not end with Z: " + str, str.endsWith("Z")); } - String str = (String)timestampValue; - assertTrue("Timestamp "+attrName+" does not start with 2: "+str, str.startsWith("2")); - assertTrue("Timestamp "+attrName+" does not end with Z: "+str, str.endsWith("Z")); } /** @@ -79,8 +80,6 @@ protected void assertTimestamp(String attrName, Object timestampValue) { @Test @Override public void test489DeleteOuSuperWithSub() throws Exception { - final String TEST_NAME = "test489DeleteOuSuperWithSub"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java b/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java index 4ded99677f2..da09b4f5eb1 100644 --- a/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java +++ b/repo/repo-common/src/test/java/com/evolveum/midpoint/repo/common/commandline/TestCommandLine.java @@ -10,6 +10,7 @@ import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.io.IOException; +import java.nio.charset.StandardCharsets; import javax.xml.namespace.QName; @@ -55,8 +56,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100PlainExecuteEcho() throws Exception { - final String TEST_NAME = "test100PlainExecuteEcho"; - if (!isOsUnix()) { displaySkip(); return; @@ -79,8 +78,6 @@ public void test100PlainExecuteEcho() throws Exception { @Test public void test110RedirExecuteEcho() throws Exception { - final String TEST_NAME = "test110RedirExecuteEcho"; - if (!isOsUnix()) { displaySkip(); return; @@ -104,7 +101,7 @@ public void test110RedirExecuteEcho() throws Exception { File targetFile = new File(MidPointTestConstants.TARGET_DIR_PATH, "echo-out"); assertTrue("Target file is not there", targetFile.exists()); - String targetFileContent = FileUtils.readFileToString(targetFile); + String targetFileContent = FileUtils.readFileToString(targetFile, StandardCharsets.UTF_8); assertEquals("Wrong target file content", "Hello World", targetFileContent); } @@ -112,5 +109,4 @@ private CommandLineScriptType getScript(File file) throws SchemaException, IOExc PrismObject report = parseObject(file); return report.asObjectable().getPostReportScript(); } - } diff --git a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java index 8ae7c739e92..8944c8cded1 100644 --- a/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java +++ b/repo/repo-sql-impl-test/src/test/java/com/evolveum/midpoint/repo/sql/ResourceModifyTest.java @@ -35,7 +35,7 @@ /** * @author Radovan Semancik */ -@ContextConfiguration(locations = {"../../../../../ctx-test.xml"}) +@ContextConfiguration(locations = { "../../../../../ctx-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class ResourceModifyTest extends BaseSQLRepoTest { @@ -59,11 +59,8 @@ public void initAnts() { @Test public void test010AddResource() throws Exception { - final String TEST_NAME = "test010AddResource"; - logger.info("===[ {} ]===", TEST_NAME); - // GIVEN - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); + OperationResult result = createOperationResult(); PrismObject resource = prismContext.parseObject(RESOURCE_OPENDJ_FILE); // WHEN @@ -81,33 +78,24 @@ public void test010AddResource() throws Exception { @Test public void test020SingleDescriptionModify() throws Exception { - final String TEST_NAME = "test020SingleDescriptionModify"; - logger.info("===[ {} ]===", TEST_NAME); - - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); + OperationResult result = createOperationResult(); singleModify(descriptionAnt, -1, result); } @Test public void test030DescriptionModifySequence() throws Exception { - final String TEST_NAME = "test030DescriptionModifySequence"; - logger.info("===[ {} ]===", TEST_NAME); - - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); + OperationResult result = createOperationResult(); - for(int i=0; i <= MAX_SEQUENCE_ITERATIONS; i++) { + for (int i = 0; i <= MAX_SEQUENCE_ITERATIONS; i++) { singleModify(descriptionAnt, i, result); } } @Test public void test040RadomModifySequence() throws Exception { - final String TEST_NAME = "test040RadomModifySequence"; - logger.info("===[ {} ]===", TEST_NAME); + OperationResult result = createOperationResult(); - OperationResult result = new OperationResult(ResourceModifyTest.class.getName()+"."+TEST_NAME); - - for(int i=0; i <= MAX_RANDOM_SEQUENCE_ITERATIONS; i++) { + for (int i = 0; i <= MAX_RANDOM_SEQUENCE_ITERATIONS; i++) { singleRandomModify(i, result); } } @@ -121,8 +109,8 @@ private void singleRandomModify(int iteration, OperationResult result) throws Ob private void singleModify(CarefulAnt ant, int iteration, OperationResult result) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { // GIVEN - ItemDelta itemDelta = ant.createDelta(iteration); - Collection> modifications = MiscSchemaUtil.createCollection(itemDelta); + ItemDelta itemDelta = ant.createDelta(iteration); + Collection> modifications = MiscSchemaUtil.createCollection(itemDelta); System.out.println("itemDelta: " + itemDelta.debugDump()); @@ -133,9 +121,8 @@ private void singleModify(CarefulAnt ant, int iteration, Operation PrismObject resourceAfter = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, result); SqlRepoTestUtil.assertVersionProgress(lastVersion, resourceAfter.getVersion()); lastVersion = resourceAfter.getVersion(); - System.out.println("Version: "+lastVersion); + System.out.println("Version: " + lastVersion); ant.assertModification(resourceAfter, iteration); } - } diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java index 222f11d87f7..7bfdded0f3a 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestAbstractRestService.java @@ -8,8 +8,6 @@ import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import java.io.File; import java.util.ArrayList; import java.util.List; @@ -19,15 +17,12 @@ import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.task.api.Task; - import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.StringUtils; import org.apache.cxf.jaxrs.client.WebClient; import org.testng.AssertJUnit; import org.testng.annotations.Test; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.Referencable; import com.evolveum.midpoint.prism.crypto.EncryptionException; @@ -39,6 +34,7 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; +import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; @@ -54,18 +50,18 @@ public abstract class TestAbstractRestService extends RestServiceInitializer { -// protected static final File BASE_DIR = new File("src/test/resources"); + // protected static final File BASE_DIR = new File("src/test/resources"); protected static final File BASE_REQ_DIR = new File("src/test/resources/req/"); // REST, reader and adder authorization - public static final String USER_DARTHADDER_FILE = "user-darthadder"; - public static final String USER_DARTHADDER_OID = "1696229e-d90a-11e4-9ce6-001e8c717e5b"; - public static final String USER_DARTHADDER_USERNAME = "darthadder"; - public static final String USER_DARTHADDER_PASSWORD = "Iamy0urUncle"; + public static final String USER_DARTHADDER_FILE = "user-darthadder"; + public static final String USER_DARTHADDER_OID = "1696229e-d90a-11e4-9ce6-001e8c717e5b"; + public static final String USER_DARTHADDER_USERNAME = "darthadder"; + public static final String USER_DARTHADDER_PASSWORD = "Iamy0urUncle"; - // Authorizations, but no password - public static final String USER_NOPASSWORD_FILE = "user-nopassword"; - public static final String USER_NOPASSWORD_USERNAME = "nopassword"; + // Authorizations, but no password + public static final String USER_NOPASSWORD_FILE = "user-nopassword"; + public static final String USER_NOPASSWORD_USERNAME = "nopassword"; public static final String ROLE_ADDER_FILE = "role-adder"; @@ -123,23 +119,18 @@ public abstract class TestAbstractRestService extends RestServiceInitializer { private static final String MODIFICATION_FORCE_PASSWORD_CHANGE = "modification-force-password-change"; private static final String EXECUTE_CREDENTIAL_RESET = "execute-credential-reset"; - protected abstract File getRepoFile(String fileBaseName); protected abstract File getRequestFile(String fileBaseName); private static final String NS_SECURITY_QUESTION_ANSWER = "http://midpoint.evolveum.com/xml/ns/public/security/question-2"; public static final String QUESTION_ID = QNameUtil.qNameToUri(new QName(NS_SECURITY_QUESTION_ANSWER, "q001")); - - public TestAbstractRestService() { super(); } @Test public void test001GetUserAdministrator() { - final String TEST_NAME = "test001GetUserAdministrator"; - WebClient client = prepareClient(); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -161,8 +152,6 @@ public void test001GetUserAdministrator() { @Test public void test002GetNonExistingUser() { - final String TEST_NAME = "test002GetNonExistingUser"; - WebClient client = prepareClient(); client.path("/users/12345"); @@ -185,8 +174,6 @@ public void test002GetNonExistingUser() { @Test public void test003GetNoAuthHeaders() { - final String TEST_NAME = "test003GetNoAuthHeaders"; - WebClient client = prepareClient(null, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -205,8 +192,6 @@ public void test003GetNoAuthHeaders() { @Test public void test004GetAuthBadUsernameNullPassword() { - final String TEST_NAME = "test004GetAuthBadUsernameNullPassword"; - WebClient client = prepareClient("NoSUCHuser", null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -225,8 +210,6 @@ public void test004GetAuthBadUsernameNullPassword() { @Test public void test005GetAuthBadUsernameEmptyPassword() { - final String TEST_NAME = "test005GetAuthBadUsernameEmptyPassword"; - WebClient client = prepareClient("NoSUCHuser", ""); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -245,8 +228,6 @@ public void test005GetAuthBadUsernameEmptyPassword() { @Test public void test006GetAuthBadUsernameBadPassword() { - final String TEST_NAME = "test006GetAuthBadUsernameBadPassword"; - WebClient client = prepareClient("NoSUCHuser", "NoSuchPassword"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -265,8 +246,6 @@ public void test006GetAuthBadUsernameBadPassword() { @Test public void test007GetAuthNoPassword() { - final String TEST_NAME = "test007GetAuthNoPassword"; - WebClient client = prepareClient(USER_ADMINISTRATOR_USERNAME, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -285,8 +264,6 @@ public void test007GetAuthNoPassword() { @Test public void test016GetAuthBadPassword() { - final String TEST_NAME = "test016GetAuthBadPassword"; - WebClient client = prepareClient(USER_ADMINISTRATOR_USERNAME, "forgot"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -305,8 +282,6 @@ public void test016GetAuthBadPassword() { @Test public void test017GetUnauthorizedUser() { - final String TEST_NAME = "test017GetUnauthorizedUser"; - WebClient client = prepareClient(USER_NOBODY_USERNAME, USER_NOBODY_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -325,8 +300,6 @@ public void test017GetUnauthorizedUser() { @Test public void test018GetUserAdministratorByCyclops() { - final String TEST_NAME = "test018GetUserAdministratorByCyclops"; - WebClient client = prepareClient(USER_CYCLOPS_USERNAME, USER_CYCLOPS_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -345,8 +318,6 @@ public void test018GetUserAdministratorByCyclops() { @Test public void test019GetUserAdministratorBySomebody() { - final String TEST_NAME = "test019GetUserAdministratorBySomebody"; - WebClient client = prepareClient(USER_SOMEBODY_USERNAME, USER_SOMEBODY_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -369,9 +340,7 @@ public void test019GetUserAdministratorBySomebody() { } @Test - public void test102AddUserTemplate() throws Exception { - final String TEST_NAME = "test102AddUserTemplate"; - + public void test102AddUserTemplate() { WebClient client = prepareClient(); client.path("/objectTemplates/"); @@ -392,9 +361,7 @@ public void test102AddUserTemplate() throws Exception { } @Test - public void test103AddUserBadTargetCollection() throws Exception { - final String TEST_NAME = "test103AddUserBadTargetCollection"; - + public void test103AddUserBadTargetCollection() { WebClient client = prepareClient(); client.path("/objectTemplates"); @@ -419,8 +386,6 @@ public void test103AddUserBadTargetCollection() throws Exception { @Test public void test104AddAccountRawResourceDoesNotExist() throws Exception { - final String TEST_NAME = "test104AddAccountRaw"; - WebClient client = prepareClient(); client.path("/shadows"); client.query("options", "raw"); @@ -437,7 +402,7 @@ public void test104AddAccountRawResourceDoesNotExist() throws Exception { assertStatus(response, 240); OperationResult addResult = traceResponse(response); assertNotNull("Expected operation result in the response, but nothing in the body", addResult); - assertEquals("Unexpected status of the operation result. Expected "+ OperationResultStatus.HANDLED_ERROR + ", but was " + addResult.getStatus(), addResult.getStatus(), OperationResultStatus.HANDLED_ERROR); + assertEquals("Unexpected status of the operation result. Expected " + OperationResultStatus.HANDLED_ERROR + ", but was " + addResult.getStatus(), addResult.getStatus(), OperationResultStatus.HANDLED_ERROR); OperationResult parentResult = new OperationResult("get"); try { @@ -458,9 +423,7 @@ public void test104AddAccountRawResourceDoesNotExist() throws Exception { } @Test - public void test120AddRoleAdder() throws Exception { - final String TEST_NAME = "test120AddRoleAdder"; - + public void test120AddRoleAdder() { WebClient client = prepareClient(); client.path("/roles"); @@ -480,9 +443,7 @@ public void test120AddRoleAdder() throws Exception { } @Test - public void test121AddUserDarthAdder() throws Exception { - final String TEST_NAME = "test121AddUserDarthAdder"; - + public void test121AddUserDarthAdder() { WebClient client = prepareClient(); client.path("/users"); @@ -502,9 +463,7 @@ public void test121AddUserDarthAdder() throws Exception { } @Test - public void test122AddRoleModifierAsDarthAdder() throws Exception { - final String TEST_NAME = "test122AddRoleModifierAsDarthAdder"; - + public void test122AddRoleModifierAsDarthAdder() { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/roles"); @@ -525,10 +484,8 @@ public void test122AddRoleModifierAsDarthAdder() throws Exception { @Test public void test123DarthAdderAssignModifierHimself() throws Exception { - final String TEST_NAME = "test123DarthAdderAssignModifierHimself"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -551,10 +508,8 @@ public void test123DarthAdderAssignModifierHimself() throws Exception { @Test public void test124DarthAdderAssignModifierByAdministrator() throws Exception { - final String TEST_NAME = "test124DarthAdderAssignModifierByAdministrator"; - WebClient client = prepareClient(); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -577,10 +532,8 @@ public void test124DarthAdderAssignModifierByAdministrator() throws Exception { @Test public void test130DarthAdderDisableHimself() throws Exception { - final String TEST_NAME = "test130DarthAdderDisableHimself"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -603,8 +556,6 @@ public void test130DarthAdderDisableHimself() throws Exception { @Test public void test131GetUserAdministratorByDarthAdder() { - final String TEST_NAME = "test131GetUserAdministratorByDarthAdder"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -624,10 +575,8 @@ public void test131GetUserAdministratorByDarthAdder() { @Test public void test132DarthAdderEnableByAdministrator() throws Exception { - final String TEST_NAME = "test132DarthAdderEnableByAdministrator"; - WebClient client = prepareClient(); - client.path("/users/"+USER_DARTHADDER_OID); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -650,8 +599,6 @@ public void test132DarthAdderEnableByAdministrator() throws Exception { @Test public void test133GetUserAdministratorByDarthAdder() { - final String TEST_NAME = "test133GetUserAdministratorByDarthAdder"; - WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -672,9 +619,7 @@ public void test133GetUserAdministratorByDarthAdder() { } @Test - public void test135AddUserNopasswordAsDarthAdder() throws Exception { - final String TEST_NAME = "test135AddUserNopasswordAsDarthAdder"; - + public void test135AddUserNopasswordAsDarthAdder() { WebClient client = prepareClient(USER_DARTHADDER_USERNAME, USER_DARTHADDER_PASSWORD); client.path("/users"); @@ -695,8 +640,6 @@ public void test135AddUserNopasswordAsDarthAdder() throws Exception { @Test public void test140GetUserAdministratorByNopassword() { - final String TEST_NAME = "test140GetUserAdministratorByNopassword"; - WebClient client = prepareClient(USER_NOPASSWORD_USERNAME, null); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -716,8 +659,6 @@ public void test140GetUserAdministratorByNopassword() { @Test public void test141GetUserAdministratorByNopasswordBadPassword() { - final String TEST_NAME = "test140GetUserAdministratorByNopassword"; - WebClient client = prepareClient(USER_NOPASSWORD_USERNAME, "bad"); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -737,8 +678,6 @@ public void test141GetUserAdministratorByNopasswordBadPassword() { @Test public void test200searchAllUsers() { - final String TEST_NAME = "test200searchAllUsers"; - WebClient client = prepareClient(); client.path("/users/search"); @@ -758,9 +697,7 @@ public void test200searchAllUsers() { } @Test - public void test401AddUserTemplateOverwrite() throws Exception { - final String TEST_NAME = "test401AddUserTemplateOverwrite"; - + public void test401AddUserTemplateOverwrite() { WebClient client = prepareClient(); client.path("/objectTemplates"); client.query("options", "overwrite"); @@ -792,9 +729,7 @@ public void test401AddUserTemplateOverwrite() throws Exception { * MID-4899 */ @Test - public void test410AddFunctionLibraryHello() throws Exception { - final String TEST_NAME = "test410AddFunctionLibraryHello"; - + public void test410AddFunctionLibraryHello() { WebClient client = prepareClient(); client.path("/functionLibraries"); client.query("options", "overwrite"); @@ -824,8 +759,6 @@ public void test410AddFunctionLibraryHello() throws Exception { @Test public void test412GetFunctionLibraryHello() { - final String TEST_NAME = "test412GetFunctionLibraryHello"; - WebClient client = prepareClient(); client.path("/functionLibraries/" + FUNCTION_LIBRARY_HELLO_OID); @@ -852,9 +785,7 @@ public void test412GetFunctionLibraryHello() { } @Test - public void test501generateValue() throws Exception { - final String TEST_NAME = "test501generateValue"; - + public void test501generateValue() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -876,9 +807,7 @@ public void test501generateValue() throws Exception { } @Test - public void test502generateValueBadPath() throws Exception { - final String TEST_NAME = "test502generateValueBadPath"; - + public void test502generateValueBadPath() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -898,9 +827,7 @@ public void test502generateValueBadPath() throws Exception { } @Test - public void test503generateValueExecute() throws Exception { - final String TEST_NAME = "test503generateValueExecute"; - + public void test503generateValueExecute() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -925,11 +852,9 @@ public void test503generateValueExecute() throws Exception { } @Test - public void test504checkGeneratedValue() throws Exception { - final String TEST_NAME = "test503generateValueExecute"; - + public void test504checkGeneratedValue() { WebClient client = prepareClient(); - client.path("/users/" + USER_DARTHADDER_OID ); + client.path("/users/" + USER_DARTHADDER_OID); getDummyAuditService().clear(); @@ -946,9 +871,7 @@ public void test504checkGeneratedValue() throws Exception { } @Test - public void test505generatePasswordExecute() throws Exception { - final String TEST_NAME = "test505generatePasswordExecute"; - + public void test505generatePasswordExecute() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -972,9 +895,7 @@ public void test505generatePasswordExecute() throws Exception { } @Test - public void test506generateHonorificPrefixNameExecute() throws Exception { - final String TEST_NAME = "test506generateHonorificPrefixNameExecute"; - + public void test506generateHonorificPrefixNameExecute() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/generate"); @@ -998,11 +919,11 @@ public void test506generateHonorificPrefixNameExecute() throws Exception { //TODO assert changed items } - private OperationResult traceResponse(Response response) throws SchemaException { + private OperationResult traceResponse(Response response) { return traceResponse(response, false); } - private OperationResult traceResponse(Response response, boolean assertMessages) throws SchemaException { + private OperationResult traceResponse(Response response, boolean assertMessages) { if (response.getStatus() != 200 && response.getStatus() != 201 && response.getStatus() != 204) { LOGGER.info("coverting result"); OperationResultType result = response.readEntity(OperationResultType.class); @@ -1036,11 +957,8 @@ private void assertLocalizableMessage(LocalizableMessageType localizableMessage) LOGGER.info("localizable message: " + localizableMessage); } - @Test - public void test510validateValueExplicit() throws Exception { - final String TEST_NAME = "test510validateValueExplicit"; - + public void test510validateValueExplicit() { WebClient client = prepareClient(); client.path("/rpc/validate"); @@ -1062,9 +980,7 @@ public void test510validateValueExplicit() throws Exception { } @Test - public void test511validateValueExplicitConflict() throws Exception { - final String TEST_NAME = "test511validateValueExplicitConflict"; - + public void test511validateValueExplicitConflict() { WebClient client = prepareClient(); client.path("/rpc/validate"); @@ -1079,16 +995,13 @@ public void test511validateValueExplicitConflict() throws Exception { assertEquals("Expected 409 but got " + response.getStatus(), 409, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @Test - public void test512validateValueImplicitSingle() throws Exception { - final String TEST_NAME = "test512validateValueImplicitSingle"; - + public void test512validateValueImplicitSingle() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1102,16 +1015,13 @@ public void test512validateValueImplicitSingle() throws Exception { assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @Test - public void test513validateValueImplicitMulti() throws Exception { - final String TEST_NAME = "test513validateValueImplicitMulti"; - + public void test513validateValueImplicitMulti() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1132,9 +1042,7 @@ public void test513validateValueImplicitMulti() throws Exception { } @Test - public void test514validateValueImplicitMultiConflict() throws Exception { - final String TEST_NAME = "test514validateValueImplicitMultiConflict"; - + public void test514validateValueImplicitMultiConflict() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1154,11 +1062,8 @@ public void test514validateValueImplicitMultiConflict() throws Exception { getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } - @Test - public void test515validatePasswordHistoryConflict() throws Exception { - final String TEST_NAME = "test515validatePasswordHistoryConflict"; - + public void test515validatePasswordHistoryConflict() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1180,9 +1085,7 @@ public void test515validatePasswordHistoryConflict() throws Exception { } @Test - public void test516validateValueExplicitNoValuePolicy() throws Exception { - final String TEST_NAME = "test516validateValueExplicitNoValuePolicy"; - + public void test516validateValueExplicitNoValuePolicy() { WebClient client = prepareClient(); client.path("/rpc/validate"); @@ -1204,9 +1107,7 @@ public void test516validateValueExplicitNoValuePolicy() throws Exception { } @Test - public void test517generateValueExplicit() throws Exception { - final String TEST_NAME = "test517generateValueExplicit"; - + public void test517generateValueExplicit() { WebClient client = prepareClient(); client.path("/rpc/generate"); @@ -1229,8 +1130,6 @@ public void test517generateValueExplicit() throws Exception { @Test public void test518validateValueImplicitPassword() throws Exception { - final String TEST_NAME = "test518validateValueImplicitPassword"; - Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject secPolicyNoHistory = parseObject(SECURITY_POLICY_NO_HISTORY); @@ -1253,8 +1152,6 @@ public void test518validateValueImplicitPassword() throws Exception { display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); - }catch (Exception ex) { - throw ex; } finally { PrismObject secPolicy = parseObject(SECURITY_POLICY); addObject(secPolicy, ModelExecuteOptions.createOverwrite(), task, result); @@ -1263,8 +1160,6 @@ public void test518validateValueImplicitPassword() throws Exception { @Test public void test520GeneratePasswordsUsingScripting() throws Exception { - final String TEST_NAME = "test520GeneratePasswordsUsingScripting"; - WebClient client = prepareClient(); client.path("/rpc/executeScript"); @@ -1317,8 +1212,6 @@ public void test520GeneratePasswordsUsingScripting() throws Exception { @Test public void test530ModifyValidToUsingScripting() throws Exception { - final String TEST_NAME = "test530ModifyValidToUsingScripting"; - WebClient client = prepareClient(); client.path("/rpc/executeScript"); @@ -1449,8 +1342,6 @@ private List> extractI */ @Test public void test600ModifySecurityQuestionReplaceAnswerId1Existing() throws Exception { - final String TEST_NAME = "test600ModifySecurityQuestionReplaceAnswerId1Existing"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1493,8 +1384,6 @@ private UserType getUserRest(String oid) { */ @Test public void test602ModifySecurityQuestionReplaceTwoAnswersExisting() throws Exception { - final String TEST_NAME = "test602ModifySecurityQuestionReplaceTwoAnswersExisting"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1529,8 +1418,6 @@ public void test602ModifySecurityQuestionReplaceTwoAnswersExisting() throws Exce */ @Test public void test604ModifySecurityQuestionReplaceNoAnswer() throws Exception { - final String TEST_NAME = "test604ModifySecurityQuestionReplaceNoAnswer"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1565,8 +1452,6 @@ public void test604ModifySecurityQuestionReplaceNoAnswer() throws Exception { */ @Test public void test606ModifySecurityQuestionReplaceAnswer() throws Exception { - final String TEST_NAME = "test606ModifySecurityQuestionReplaceAnswer"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1597,9 +1482,7 @@ public void test606ModifySecurityQuestionReplaceAnswer() throws Exception { } @Test - public void test607validateSecurityAnswerCheckExpressionFail() throws Exception { - final String TEST_NAME = "test607validateSecurityAnswerCheckExpressionFail"; - + public void test607validateSecurityAnswerCheckExpressionFail() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1614,16 +1497,13 @@ public void test607validateSecurityAnswerCheckExpressionFail() throws Exception assertEquals("Expected 409 but got " + response.getStatus(), 409, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); } @Test - public void test608validateSecurityAnswerCheckExpression() throws Exception { - final String TEST_NAME = "test607validateSecurityAnswerCheckExpression"; - + public void test608validateSecurityAnswerCheckExpression() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/validate"); @@ -1637,7 +1517,6 @@ public void test608validateSecurityAnswerCheckExpression() throws Exception { assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(2); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -1671,7 +1550,7 @@ private void assertSecurityQuestionAnswers(UserType userType, String expectedAns assertEquals("Unexpected security question 001 answer in " + userType, expectedAnswer001, decrypted); } - private void assertSecurityQuestionNoAnswer(UserType userType) throws EncryptionException { + private void assertSecurityQuestionNoAnswer(UserType userType) { CredentialsType credentials = userType.getCredentials(); assertNotNull("No credentials in user. Something is wrong.", credentials); SecurityQuestionsCredentialsType securityQuestions = credentials.getSecurityQuestions(); @@ -1682,21 +1561,19 @@ private void assertSecurityQuestionNoAnswer(UserType userType) throws Encryption private void assertSecurityQuestionAnswer(List secQuestionAnswers, String anwerUriLocalPart, String expectedAnswer) throws EncryptionException { - for (SecurityQuestionAnswerType secQuestionAnswer: secQuestionAnswers) { + for (SecurityQuestionAnswerType secQuestionAnswer : secQuestionAnswers) { if (secQuestionAnswer.getQuestionIdentifier().equals(QNameUtil.qNameToUri( new QName(NS_SECURITY_QUESTION_ANSWER, anwerUriLocalPart)))) { String decrypted = getPrismContext().getDefaultProtector().decryptString(secQuestionAnswer.getQuestionAnswer()); - assertEquals("Unexpected security question "+anwerUriLocalPart+" answer", expectedAnswer, decrypted); + assertEquals("Unexpected security question " + anwerUriLocalPart + " answer", expectedAnswer, decrypted); return; } } - AssertJUnit.fail("Security question answer "+anwerUriLocalPart+" not found"); + AssertJUnit.fail("Security question answer " + anwerUriLocalPart + " not found"); } @Test - public void test610ModifyPasswordForceChange() throws Exception { - final String TEST_NAME = "test610ModifyPasswordForceChange"; - + public void test610ModifyPasswordForceChange() { WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID); @@ -1711,7 +1588,6 @@ public void test610ModifyPasswordForceChange() throws Exception { assertEquals("Expected 204 but got " + response.getStatus(), 204, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -1735,8 +1611,6 @@ public void test610ModifyPasswordForceChange() throws Exception { @Test public void test612ResetPassword() throws Exception { - final String TEST_NAME = "test612ResetPassword"; - WebClient client = prepareClient(); client.path("/users/" + USER_DARTHADDER_OID + "/credential"); @@ -1754,7 +1628,6 @@ public void test612ResetPassword() throws Exception { assertEquals("Expected 200 but got " + response.getStatus(), 200, response.getStatus()); - display("Audit", getDummyAuditService()); getDummyAuditService().assertRecords(4); getDummyAuditService().assertLoginLogout(SchemaConstants.CHANNEL_REST_URI); @@ -1782,8 +1655,6 @@ public void test612ResetPassword() throws Exception { @Test // MID-4928 public void test650SuspendNonExistingTask() { - final String TEST_NAME = "test650SuspendNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456/suspend"); @@ -1798,8 +1669,6 @@ public void test650SuspendNonExistingTask() { @Test // MID-4928 public void test652SuspendWrongObject() { - final String TEST_NAME = "test652SuspendWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002/suspend"); @@ -1814,8 +1683,6 @@ public void test652SuspendWrongObject() { @Test // MID-4928 public void test660ResumeNonExistingTask() { - final String TEST_NAME = "test660ResumeNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456/resume"); @@ -1830,8 +1697,6 @@ public void test660ResumeNonExistingTask() { @Test // MID-4928 public void test662ResumeWrongObject() { - final String TEST_NAME = "test662ResumeWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002/resume"); @@ -1846,8 +1711,6 @@ public void test662ResumeWrongObject() { @Test // MID-4928 public void test670ScheduleNonExistingTask() { - final String TEST_NAME = "test670ScheduleNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456/run"); @@ -1862,8 +1725,6 @@ public void test670ScheduleNonExistingTask() { @Test // MID-4928 public void test672ScheduleWrongObject() { - final String TEST_NAME = "test672ScheduleWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002/run"); @@ -1878,8 +1739,6 @@ public void test672ScheduleWrongObject() { @Test // MID-4928 public void test680DeleteNonExistingTask() { - final String TEST_NAME = "test680DeleteNonExistingTask"; - WebClient client = prepareClient(); client.path("/tasks/123456"); @@ -1894,8 +1753,6 @@ public void test680DeleteNonExistingTask() { @Test // MID-4928 public void test682DeleteWrongObject() { - final String TEST_NAME = "test682DeleteWrongObject"; - WebClient client = prepareClient(); client.path("/tasks/00000000-0000-0000-0000-000000000002"); @@ -1908,18 +1765,10 @@ public void test682DeleteWrongObject() { assertEquals("Expected 400 but got " + response.getStatus(), 400, response.getStatus()); } - - - private WebClient prepareClient() { return prepareClient(USER_ADMINISTRATOR_USERNAME, USER_ADMINISTRATOR_PASSWORD); } - private void assertNoEmptyResponse(Response response) { - String respBody = response.readEntity(String.class); - assertTrue("Unexpected reposponse: "+respBody, StringUtils.isBlank(respBody)); - } - private void displayResponse(Response response) { LOGGER.info("response : {} ", response.getStatus()); LOGGER.info("response : {} ", response.getStatusInfo().getReasonPhrase()); diff --git a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java index 9eaa647129a..565ce45d9e7 100644 --- a/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java +++ b/testing/rest/src/test/java/com/evolveum/midpoint/testing/rest/TestRestServiceProxyAuthentication.java @@ -68,8 +68,6 @@ public void initSystem(Task initTask, OperationResult result) throws Exception { @Test public void test001getUserSelfBySomebody() { - final String TEST_NAME = "test001getUserSelfBySomebody"; - WebClient client = prepareClient(USER_SOMEBODY_OID); client.path("/self/"); @@ -91,8 +89,6 @@ public void test001getUserSelfBySomebody() { @Test public void test002getUserSelfByEgoist() { - final String TEST_NAME = "test002getUserSelfByEgoist"; - WebClient client = prepareClient(USER_EGOIST_OID); client.path("/self/"); @@ -118,8 +114,6 @@ public void test002getUserSelfByEgoist() { */ @Test public void test003getUserAdministratorByEgoist() { - final String TEST_NAME = "test003getUserAdministratorByEgoist"; - WebClient client = prepareClient(USER_EGOIST_OID); client.path("/users/" + SystemObjectsType.USER_ADMINISTRATOR.value()); @@ -141,8 +135,6 @@ public void test003getUserAdministratorByEgoist() { */ @Test public void test004getUserSelfByHead() { - final String TEST_NAME = "test004getUserSelfByHead"; - WebClient client = prepareClient(null); client.path("/self"); @@ -168,8 +160,6 @@ public void test004getUserSelfByHead() { */ @Test public void test005getUserSelfByProxyHead() { - final String TEST_NAME = "test005getUserSelfByProxyHead"; - WebClient client = prepareClient(USER_HEAD_OID); client.path("/self"); diff --git a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java index 6bbdc33cff3..e1d51dcf131 100644 --- a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java +++ b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java @@ -340,7 +340,6 @@ public static void stopResources() throws Exception { */ @Test public void test000Integrity() throws Exception { - final String TEST_NAME = "test000Integrity"; assertNotNull(modelWeb); assertNotNull(modelService); assertNotNull(repositoryService); @@ -380,11 +379,9 @@ public void test000Integrity() throws Exception { * Repeat self-test when we have all the dependencies on the classpath. */ @Test - public void test001SelfTests() throws Exception { - final String TEST_NAME = "test001SelfTests"; - + public void test001SelfTests() { // GIVEN - Task task = taskManager.createTaskInstance(TestSanity.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); // WHEN OperationResult repositorySelfTestResult = modelDiagnosticService.repositorySelfTest(task); @@ -409,8 +406,6 @@ public void test001SelfTests() throws Exception { */ @Test public void test001TestConnectionOpenDJ() throws Exception { - final String TEST_NAME = "test001TestConnectionOpenDJ"; - // GIVEN try { assertNoRepoCache(); @@ -469,8 +464,6 @@ private void checkRepoOpenDjResource() throws ObjectNotFoundException, SchemaExc /** * Checks if the resource is internally consistent, if it has everything it should have. - * - * @throws SchemaException */ private void checkOpenDjResource(ResourceType resource, String source) throws SchemaException { assertNotNull("Resource from " + source + " is null", resource); @@ -584,10 +577,8 @@ private void checkOpenResourceConfiguration(PrismObject resource, @Test public void test002AddDerbyResource() throws Exception { - final String TEST_NAME = "test002AddDerbyResource"; - // GIVEN - OperationResult result = new OperationResult(TestSanity.class.getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); checkRepoOpenDjResource(); assertNoRepoCache(); @@ -737,7 +728,7 @@ public void test003TestConnectionDerby() throws Exception { @Test public void test004Capabilities() - throws ObjectNotFoundException, CommunicationException, SchemaException, FaultMessage { + throws ObjectNotFoundException, SchemaException, FaultMessage { // GIVEN checkRepoOpenDjResource(); @@ -842,8 +833,7 @@ public void test006reimportResourceDummy() throws Exception { fail("Expected object already exists exception, but haven't got one."); } catch (FaultMessage ex) { - logger.info("fault {}", ex.getFaultInfo()); - logger.info("fault {}", ex.getCause()); + logger.info("fault {}", ex.getFaultInfo(), ex.getCause()); if (ex.getFaultInfo() instanceof ObjectAlreadyExistsFaultType) { // this is OK, we expect this } else { @@ -864,8 +854,6 @@ public void test006reimportResourceDummy() throws Exception { */ @Test public void test010AddUser() throws Exception { - final String TEST_NAME = "test010AddUser"; - // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); @@ -915,7 +903,6 @@ public void test010AddUser() throws Exception { */ @Test public void test013AddOpenDjAccountToUser() throws Exception { - final String TEST_NAME = "test013AddOpenDjAccountToUser"; try { // GIVEN checkRepoOpenDjResource(); @@ -1033,7 +1020,7 @@ public void test013AddOpenDjAccountToUser() throws Exception { assertNotNull("Activation is null (model)", modelShadow.getActivation()); assertEquals("Wrong administrativeStatus in the shadow (model)", ActivationStatusType.ENABLED, modelShadow.getActivation().getAdministrativeStatus()); } catch (Exception ex) { - logger.info("ERROR: {}", ex); + logger.info("ERROR", ex); throw ex; } @@ -1160,7 +1147,7 @@ public void test014AddDerbyAccountToUser() throws IOException, JAXBException, Fa } @Test - public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException, JAXBException { + public void test015AccountOwner() throws FaultMessage, ObjectNotFoundException, SchemaException { // GIVEN checkRepoOpenDjResource(); assertNoRepoCache(); @@ -1244,7 +1231,6 @@ public boolean handle(PrismObject prismObject, OperationResult paren */ @Test public void test020ModifyUser() throws Exception { - final String TEST_NAME = "test020ModifyUser"; // GIVEN assertNoRepoCache(); @@ -1341,7 +1327,6 @@ private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) */ @Test public void test022ChangeUserPassword() throws Exception { - final String TEST_NAME = "test022ChangeUserPassword"; // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -1362,8 +1347,6 @@ public void test022ChangeUserPassword() throws Exception { */ @Test public void test023ChangeUserPasswordJAXB() throws Exception { - final String TEST_NAME = "test023ChangeUserPasswordJAXB"; - // GIVEN final String NEW_PASSWORD = "abandonSHIP"; Document doc = ModelClientUtil.getDocumnent(); @@ -1391,7 +1374,7 @@ public void test023ChangeUserPasswordJAXB() throws Exception { assertUserPasswordChange(NEW_PASSWORD, result); } - private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws JAXBException, ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException { + private void assertUserPasswordChange(String expectedUserPassword, OperationResultType result) throws ObjectNotFoundException, SchemaException, DirectoryException, EncryptionException { assertNoRepoCache(); displayJaxb("modifyObject result:", result, SchemaConstants.C_RESULT); TestUtil.assertSuccess("modifyObject has failed", result); @@ -1444,17 +1427,15 @@ private void assertUserPasswordChange(String expectedUserPassword, OperationResu @Test public void test027ModifyAccountDj() throws Exception { - final String TEST_NAME = "test027ModifyAccountDj"; - testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck"); + testModifyAccountDjRoomNumber(REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_FILE, "quarterdeck"); } @Test public void test028ModifyAccountDjExplicitType() throws Exception { - final String TEST_NAME = "test028ModifyAccountDjExplicitType"; - testModifyAccountDjRoomNumber(TEST_NAME, REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck"); + testModifyAccountDjRoomNumber(REQUEST_ACCOUNT_MODIFY_ROOM_NUMBER_EXPLICIT_TYPE_FILE, "upperdeck"); } - public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, String expectedVal) throws Exception { + public void testModifyAccountDjRoomNumber(File reqFile, String expectedVal) throws Exception { // GIVEN assertNoRepoCache(); @@ -1489,7 +1470,6 @@ public void testModifyAccountDjRoomNumber(final String TEST_NAME, File reqFile, @Test public void test029ModifyAccountDjBadPath() throws Exception { - final String TEST_NAME = "test029ModifyAccountDjBadPath"; // GIVEN assertNoRepoCache(); @@ -1537,9 +1517,7 @@ public void test029ModifyAccountDjBadPath() throws Exception { */ @Test public void test030DisableUser() throws Exception { - final String TEST_NAME = "test030DisableUser"; // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME, ObjectDeltaType.class); @@ -1649,9 +1627,7 @@ public void test030DisableUser() throws Exception { */ @Test public void test031EnableUser() throws Exception { - final String TEST_NAME = "test031EnableUser"; // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class); assertNoRepoCache(); @@ -1848,9 +1824,7 @@ private OperationResultType deleteObjectViaModelWS(QName typeQName, String oid) @Test public void test047RenameUser() throws Exception { - final String TEST_NAME = "test047RenameUser"; // GIVEN - assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -1906,13 +1880,9 @@ public void test047RenameUser() throws Exception { /** * We are going to modify the user. As the user has an account, the user * changes should be also applied to the account (by schemaHandling). - * - * @throws DirectoryException */ @Test public void test048ModifyUserRemoveGivenName() throws Exception { - final String TEST_NAME = "test048ModifyUserRemoveGivenName"; - // GIVEN assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -1967,8 +1937,6 @@ public void test048ModifyUserRemoveGivenName() throws Exception { /** * The user should have an account now. Let's try to delete the user. The * account should be gone as well. - * - * @throws JAXBException */ @Test public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryException { @@ -2015,8 +1983,6 @@ public void test049DeleteUser() throws SchemaException, FaultMessage, DirectoryE @Test public void test100AssignRolePirate() throws Exception { - final String TEST_NAME = "test100AssignRolePirate"; - // GIVEN // IMPORTANT! Assignment enforcement is FULL now @@ -2110,8 +2076,6 @@ public void test100AssignRolePirate() throws Exception { @Test public void test101AccountOwnerAfterRole() throws Exception { - final String TEST_NAME = "test101AccountOwnerAfterRole"; - // GIVEN assertNoRepoCache(); @@ -2135,8 +2099,6 @@ public void test101AccountOwnerAfterRole() throws Exception { @Test public void test102AssignRoleCaptain() throws Exception { - final String TEST_NAME = "test102AssignRoleCaptain"; - // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -2215,8 +2177,6 @@ public void test102AssignRoleCaptain() throws Exception { */ @Test public void test103AssignRoleCaptainAgain() throws Exception { - final String TEST_NAME = "test103AssignRoleCaptainAgain"; - // GIVEN ObjectDeltaType objectChange = unmarshallValueFromFile( @@ -2292,10 +2252,7 @@ public void test103AssignRoleCaptainAgain() throws Exception { @Test public void test105ModifyAccount() throws Exception { - final String TEST_NAME = "test105ModifyAccount"; - // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidGuybrushOpendj); @@ -2304,7 +2261,7 @@ public void test105ModifyAccount() throws Exception { OperationResultType result = modifyObjectViaModelWS(objectChange); Task task = taskManager.createTaskInstance(); - OperationResult parentResult = new OperationResult(TEST_NAME + "-get after first modify"); + OperationResult parentResult = createOperationResult("get after first modify"); PrismObject shadow = modelService.getObject(ShadowType.class, accountShadowOidGuybrushOpendj, null, task, parentResult); assertNotNull("shadow must not be null", shadow); @@ -2375,10 +2332,7 @@ public void test105ModifyAccount() throws Exception { */ @Test public void test104AssignRoleJudge() throws Exception { - final String TEST_NAME = "test104AssignRoleJudge"; - // GIVEN - OperationResultType result = new OperationResultType(); Holder resultHolder = new Holder<>(result); Holder oidHolder = new Holder<>(); @@ -2418,18 +2372,14 @@ public void test104AssignRoleJudge() throws Exception { @Test public void test107UnassignRolePirate() throws Exception { - final String TEST_NAME = "test107UnassignRolePirate"; - // GIVEN - - OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), - result = modifyObjectViaModelWS(objectChange); + OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); @@ -2498,18 +2448,14 @@ public void test107UnassignRolePirate() throws Exception { @Test public void test108UnassignRoleCaptain() throws Exception { - final String TEST_NAME = "test108UnassignRoleCaptain"; - // GIVEN - - OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), - result = modifyObjectViaModelWS(objectChange); + OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); @@ -2583,18 +2529,15 @@ public void test108UnassignRoleCaptain() throws Exception { */ @Test public void test109UnassignRoleCaptainAgain() throws Exception { - final String TEST_NAME = "test109UnassignRoleCaptainAgain"; - // GIVEN - OperationResultType result = new OperationResultType(); assertNoRepoCache(); ObjectDeltaType objectChange = unmarshallValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), - result = modifyObjectViaModelWS(objectChange); + OperationResultType result = modifyObjectViaModelWS(objectChange); // THEN assertNoRepoCache(); @@ -2606,7 +2549,6 @@ public void test109UnassignRoleCaptainAgain() throws Exception { // Check if user object was modified in the repo OperationResult repoResult = new OperationResult("getObject"); - PropertyReferenceListType resolve = new PropertyReferenceListType(); PrismObject repoUser = repositoryService.getObject(UserType.class, USER_GUYBRUSH_OID, null, repoResult); UserType repoUserType = repoUser.asObjectable(); @@ -2648,7 +2590,6 @@ public void test109UnassignRoleCaptainAgain() throws Exception { */ @Test public void test300LiveSyncInit() throws Exception { - final String TEST_NAME = "test300LiveSyncInit"; // Now it is the right time to add task definition to the repository // We don't want it there any sooner, as it may interfere with the // previous tests @@ -2660,8 +2601,7 @@ public void test300LiveSyncInit() throws Exception { // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.POSITIVE); - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); repoAddObjectFromFile(TASK_OPENDJ_SYNC_FILENAME, result); @@ -2757,12 +2697,10 @@ public void timeout() { */ @Test public void test301LiveSyncCreate() throws Exception { - final String TEST_NAME = "test301LiveSyncCreate"; // Sync task should be running (tested in previous test), so just create // new LDAP object. - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2796,10 +2734,7 @@ public void test301LiveSyncCreate() throws Exception { @Test public void test302LiveSyncModify() throws Exception { - final String TEST_NAME = "test302LiveSyncModify"; - - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2828,8 +2763,6 @@ public void test302LiveSyncModify() throws Exception { @Test public void test303LiveSyncLink() throws Exception { - final String TEST_NAME = "test303LiveSyncLink"; - // GIVEN assertNoRepoCache(); PrismObject user = PrismTestUtil.parseObject(USER_E_LINK_ACTION_FILE); @@ -2853,8 +2786,7 @@ public void test303LiveSyncLink() throws Exception { when(); //create account for e which should be correlated - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2893,12 +2825,10 @@ public void test303LiveSyncLink() throws Exception { */ @Test public void test304LiveSyncCreateNoLocation() throws Exception { - final String TEST_NAME = "test304LiveSyncCreateNoLocation"; // Sync task should be running (tested in previous test), so just create // new LDAP object. - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); @@ -2966,9 +2896,7 @@ private Object findSyncTokenObject(Task syncCycle) { */ @Test public void test399LiveSyncCleanup() throws Exception { - final String TEST_NAME = "test399LiveSyncCleanup"; - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.deleteTask(TASK_OPENDJ_SYNC_OID, result); @@ -2977,13 +2905,11 @@ public void test399LiveSyncCleanup() throws Exception { @Test public void test400ImportFromResource() throws Exception { - final String TEST_NAME = "test400ImportFromResource"; // GIVEN checkAllShadows(); assertNoRepoCache(); - OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + OperationResult result = createOperationResult(); // Make sure Mr. Gibbs has "l" attribute set to the same value as an outbound expression is setting ChangeRecordEntry entry = openDJController.executeLdifChange(LDIF_GIBBS_MODIFY_FILE); @@ -3192,11 +3118,9 @@ private String getUserLocality(UserType user) { @Test public void test420RecomputeUsers() throws Exception { - final String TEST_NAME = "test420RecomputeUsers"; // GIVEN - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); // Assign role to a user, but we do this using a repository instead of model. // The role assignment will not be executed and this created an inconsistent state. @@ -3332,11 +3256,9 @@ public void timeout() { @Test public void test440ReconcileResourceOpenDj() throws Exception { - final String TEST_NAME = "test440ReconcileResourceOpenDj"; // GIVEN - final OperationResult result = new OperationResult(TestSanity.class.getName() - + "." + TEST_NAME); + final OperationResult result = createOperationResult(); // Create LDAP account without an owner. The liveSync is off, so it will not be picked up @@ -3550,7 +3472,6 @@ public void timeout() { @Test public void test480ListResources() throws Exception { - final String TEST_NAME = "test480ListResources"; // GIVEN OperationResultType result = new OperationResultType(); Holder resultHolder = new Holder<>(result); @@ -3672,9 +3593,6 @@ public void test500NotifyChangeCreateAccount() throws Exception { @Test public void test501NotifyChangeModifyAccount() throws Exception { - final String TEST_NAME = "test501NotifyChangeModifyAccount"; - - OperationResult parentResult = createOperationResult(); PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); @@ -3728,8 +3646,6 @@ public void test501NotifyChangeModifyAccount() throws Exception { @Test public void test502NotifyChangeModifyAccountPassword() throws Exception { - final String TEST_NAME = "test502NotifyChangeModifyAccountPassword"; - PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); @@ -3784,8 +3700,6 @@ public void test502NotifyChangeModifyAccountPassword() throws Exception { @Test public void test503NotifyChangeDeleteAccount() throws Exception { - final String TEST_NAME = "test503NotifyChangeDeleteAccount"; - PrismObject userAngelika = findUserByUsername(ANGELIKA_NAME); assertNotNull("User with the name angelika must exist.", userAngelika); @@ -3978,7 +3892,7 @@ private void assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnfor assertEquals("Assignment policy mismatch", assignmentPolicy, assignmentPolicyEnforcement); } - private void checkAllShadows() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException { + private void checkAllShadows() throws SchemaException { logger.trace("Checking all shadows"); System.out.println("Checking all shadows"); ObjectChecker checker = null; From d9f1693e9d28588dec1b22d451f0aae18b0d9973 Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Sun, 8 Mar 2020 07:47:44 +0100 Subject: [PATCH 24/55] save&run button for task, introducing taskMainPanel, fixing refresh behaviour, small cleanup --- .../midpoint/gui/api/page/PageBase.java | 129 +--- .../midpoint/gui/api/prism/ItemWrapper.java | 164 ++--- .../api/util/ObjectTabVisibleBehavior.java | 257 +++---- .../PrismObjectWrapperFactoryImpl.java | 472 +++++-------- .../gui/impl/prism/ItemWrapperImpl.java | 17 +- .../prism/PrismContainerValueWrapperImpl.java | 18 +- .../impl/prism/PrismContainerWrapperImpl.java | 12 +- .../AbstractObjectMainPanel.java | 642 ++++++++--------- .../objectdetails/AbstractObjectTabPanel.java | 275 ++++---- .../objectdetails/AbstractRoleMainPanel.java | 653 +++++++++--------- ...signmentHolderTypeAssignmentsTabPanel.java | 132 ++-- .../AssignmentHolderTypeDetailsTabPanel.java | 158 ++--- .../AssignmentHolderTypeMainPanel.java | 244 ++++--- .../objectdetails/FocusMainPanel.java | 630 ++++++++--------- .../web/component/refresh/Refreshable.java | 70 +- .../web/page/admin/PageAdminAbstractRole.java | 108 ++- .../web/page/admin/PageAdminFocus.java | 152 +--- .../page/admin/PageAdminObjectDetails.java | 72 +- .../page/admin/archetype/PageArchetype.java | 258 +++---- .../web/page/admin/server/PageTask.java | 419 ++--------- .../web/page/admin/server/TaskMainPanel.html | 17 + .../web/page/admin/server/TaskMainPanel.java | 345 +++++++++ .../page/admin/server/TaskTabsVisibility.java | 22 +- .../web/page/admin/users/PageUser.java | 74 +- .../000-system-configuration.xml | 3 +- 25 files changed, 2448 insertions(+), 2895 deletions(-) create mode 100644 gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.html create mode 100644 gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java index ab4dec89393..07021336d90 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java @@ -15,13 +15,10 @@ import javax.management.ObjectName; import javax.xml.namespace.QName; -import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; - import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.commons.lang3.ObjectUtils; import org.apache.wicket.*; -import org.apache.wicket.ajax.AbstractDefaultAjaxBehavior; import org.apache.wicket.ajax.AjaxChannel; import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; @@ -35,8 +32,6 @@ import org.apache.wicket.markup.ComponentTag; import org.apache.wicket.markup.head.CssHeaderItem; import org.apache.wicket.markup.head.IHeaderResponse; -import org.apache.wicket.markup.head.JavaScriptHeaderItem; -import org.apache.wicket.markup.head.OnDomReadyHeaderItem; import org.apache.wicket.markup.html.TransparentWebMarkupContainer; import org.apache.wicket.markup.html.WebMarkupContainer; import org.apache.wicket.markup.html.WebPage; @@ -80,10 +75,14 @@ import com.evolveum.midpoint.gui.impl.factory.ItemWrapperFactory; import com.evolveum.midpoint.gui.impl.factory.PrismObjectWrapperFactory; import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.gui.impl.prism.*; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettings; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValuePanel; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; +import com.evolveum.midpoint.gui.impl.prism.PrismValueWrapper; import com.evolveum.midpoint.model.api.*; -import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; +import com.evolveum.midpoint.model.api.authentication.GuiProfiledPrincipal; import com.evolveum.midpoint.model.api.expr.MidpointFunctions; import com.evolveum.midpoint.model.api.interaction.DashboardService; import com.evolveum.midpoint.model.api.validator.ResourceValidator; @@ -159,15 +158,16 @@ import com.evolveum.midpoint.web.page.admin.resources.*; import com.evolveum.midpoint.web.page.admin.roles.PageRole; import com.evolveum.midpoint.web.page.admin.roles.PageRoles; -import com.evolveum.midpoint.web.page.admin.server.*; +import com.evolveum.midpoint.web.page.admin.server.PageNodes; +import com.evolveum.midpoint.web.page.admin.server.PageTask; +import com.evolveum.midpoint.web.page.admin.server.PageTasks; +import com.evolveum.midpoint.web.page.admin.server.PageTasksCertScheduling; import com.evolveum.midpoint.web.page.admin.services.PageService; import com.evolveum.midpoint.web.page.admin.services.PageServices; import com.evolveum.midpoint.web.page.admin.users.PageOrgTree; import com.evolveum.midpoint.web.page.admin.users.PageOrgUnit; import com.evolveum.midpoint.web.page.admin.users.PageUser; import com.evolveum.midpoint.web.page.admin.users.PageUsers; -import com.evolveum.midpoint.web.page.admin.valuePolicy.PageValuePolicies; -import com.evolveum.midpoint.web.page.admin.valuePolicy.PageValuePolicy; import com.evolveum.midpoint.web.page.admin.workflow.PageAttorneySelection; import com.evolveum.midpoint.web.page.admin.workflow.PageWorkItemsAttorney; import com.evolveum.midpoint.web.page.login.PageLogin; @@ -686,19 +686,6 @@ public void authorize(String operat getSecurityEnforcer().authorize(operationUrl, phase, params, ownerResolver, getPageTask(), result); } - public void authorize(String operationUrl, AuthorizationPhaseType phase, - PrismObject object, ObjectDelta delta, PrismObject target, OwnerResolver ownerResolver) - throws SecurityViolationException, SchemaException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException { - Task task = getPageTask(); - AuthorizationParameters params = new AuthorizationParameters.Builder() - .oldObject(object) - .delta(delta) - .target(target) - .build(); - getSecurityEnforcer().authorize(operationUrl, phase, params, ownerResolver, task, task.getResult()); - } - - public MidpointFormValidatorRegistry getFormValidatorRegistry() { return formValidatorRegistry; } @@ -1185,10 +1172,6 @@ public String getMainPopupBodyId() { return getMainPopup().getContentId(); } - public void setMainPopupTitle(IModel title) { - getMainPopup().setTitle(title); - } - public void showMainPopup(Popupable popupable, AjaxRequestTarget target) { getMainPopup().setTitle(popupable.getTitle()); getMainPopup().setInitialHeight(popupable.getHeight()); @@ -1542,61 +1525,6 @@ public String getDescribe() { return getString("pageBase.unknownBuildNumber"); } - protected ModalWindow createModalWindow(final String id, IModel title, int width, int height) { - final ModalWindow modal = new ModalWindow(id); - add(modal); - - modal.setResizable(false); - modal.setTitle(title); - modal.setCookieName(PageBase.class.getSimpleName() + ((int) (Math.random() * 100))); - - modal.setInitialWidth(width); - modal.setWidthUnit("px"); - modal.setInitialHeight(height); - modal.setHeightUnit("px"); - - modal.setCloseButtonCallback(new ModalWindow.CloseButtonCallback() { - - private static final long serialVersionUID = 1L; - - @Override - public boolean onCloseButtonClicked(AjaxRequestTarget target) { - return true; - } - }); - - modal.setWindowClosedCallback(new ModalWindow.WindowClosedCallback() { - - private static final long serialVersionUID = 1L; - - @Override - public void onClose(AjaxRequestTarget target) { - modal.close(target); - } - }); - - modal.add(new AbstractDefaultAjaxBehavior() { - - private static final long serialVersionUID = 1L; - - @Override - public void renderHead(Component component, IHeaderResponse response) { - response.render(OnDomReadyHeaderItem.forScript("Wicket.Window.unloadConfirmation = false;")); - response.render(JavaScriptHeaderItem - .forScript("$(document).ready(function() {\n" + " $(document).bind('keyup', function(evt) {\n" - + " if (evt.keyCode == 27) {\n" + getCallbackScript() + "\n" - + " evt.preventDefault();\n" + " }\n" + " });\n" + "});", id)); - } - - @Override - protected void respond(AjaxRequestTarget target) { - modal.close(target); - } - }); - - return modal; - } - // returns to previous page via restart response exception public RestartResponseException getRestartResponseException(Class defaultBackPageClass) { return new RestartResponseException(defaultBackPageClass); @@ -1755,11 +1683,6 @@ protected List createMenuItems() { AuthorizationConstants.AUTZ_UI_RESOURCE_EDIT_URL, AuthorizationConstants.AUTZ_UI_RESOURCES_VIEW_URL)) { items.add(createResourcesItems()); } - //TODO uncomment after ValuePolicies pages are finished -// if (WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_VALUE_POLICIES_URL, AuthorizationConstants.AUTZ_GUI_ALL_URL, -// AuthorizationConstants.AUTZ_UI_VALUE_POLICIES_ALL_URL, AuthorizationConstants.AUTZ_GUI_ALL_DEPRECATED_URL)) { -// items.add(createValuePolicieItems()); -// } if (WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_MY_WORK_ITEMS_URL, AuthorizationConstants.AUTZ_UI_ATTORNEY_WORK_ITEMS_URL, @@ -1953,8 +1876,6 @@ private MainMenuItem createServerTasksItems() { addMenuItem(item, "PageAdmin.menu.top.serverTasks.nodes", PageNodes.class); - //should we support archetype view for TaskType? -// addCollectionsMenuItems(item.getItems(), TaskType.COMPLEX_TYPE); MenuItem newTaskMenu = new MenuItem(createStringResource("PageAdmin.menu.top.serverTasks.new"), GuiStyleConstants.CLASS_PLUS_CIRCLE, PageTask.class, null, new VisibleEnableBehaviour()); item.getItems().add(newTaskMenu); @@ -1990,16 +1911,6 @@ private MainMenuItem createResourcesItems() { return item; } - // Izolated until the referenced value policies pages are fully implemented - private MainMenuItem createValuePolicieItems() { - MainMenuItem item = new MainMenuItem("fa fa-asterisk", createStringResource("PageAdmin.menu.top.valuePolicies"), null); - - addMenuItem(item, "PageAdmin.menu.top.valuePolicies.list", PageValuePolicies.class); - addMenuItem(item, "PageAdmin.menu.top.valuePolicies.new", PageValuePolicy.class); - - return item; - } - private MainMenuItem createReportsItems() { MainMenuItem item = new MainMenuItem("fa fa-pie-chart", createStringResource("PageAdmin.menu.top.reports"), null); @@ -2428,20 +2339,6 @@ public boolean isEnabled() { }; } - public DeploymentInformationType loadDeploymentInformationType() { - DeploymentInformationType deploymentInformationType = null; - OperationResult result = new OperationResult(OPERATION_GET_DEPLOYMENT_INFORMATION); - try { - deploymentInformationType = getModelInteractionService().getDeploymentInformationConfiguration(result); - LOGGER.trace("Deployment information : {}", deploymentInformationType); - result.recordSuccess(); - } catch (Exception ex) { - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load deployment information", ex); - result.recordFatalError(createStringResource("PageBase.message.loadDeploymentInformationType.fatalError").getString(), ex); - } - return deploymentInformationType; - } - public boolean canRedirectBack() { return canRedirectBack(DEFAULT_BREADCRUMB_STEP); } @@ -2777,16 +2674,10 @@ public Panel initItemPanel(String panelId, QName typeNa public , C extends Containerable> Panel initContainerValuePanel(String id, IModel model, ItemPanelSettings settings) { - //ItemVisibilityHandler visibilityHandler, ItemEditabilityHandler editabilityHandler) { //TODO find from registry first return new PrismContainerValuePanel<>(id, model, settings); } - public Panel getBasicContainerValuePanel(String idPanel, IModel> model, ItemPanelSettings settings){ - Panel containerValue = initContainerValuePanel(idPanel, model, settings); - return containerValue; - } - public Clock getClock() { return clock; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java index 909fa9a5666..f453815ab48 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/prism/ItemWrapper.java @@ -1,81 +1,83 @@ -/* - * Copyright (c) 2010-2018 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.gui.api.prism; - -import java.io.Serializable; -import java.util.Collection; -import java.util.List; - -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; -import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; -import com.evolveum.midpoint.gui.impl.prism.PrismValueWrapper; -import com.evolveum.midpoint.prism.Item; -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.Revivable; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.util.DebugDumpable; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -/** - * @author katka - * - */ -public interface ItemWrapper, ID extends ItemDefinition, VW extends PrismValueWrapper> extends ItemDefinition, Revivable, DebugDumpable, Serializable { - - - String debugDump(int indent); - - boolean isVisible(PrismContainerValueWrapper parentContainer, ItemVisibilityHandler visibilityHandler); - - boolean checkRequired(PageBase pageBase); - - PrismContainerValueWrapper getParent(); - - boolean isShowEmpty(); - - void setShowEmpty(boolean isShowEmpty, boolean recursive); - - boolean isShowInVirtualContainer(); - - void setShowInVirtualContainer(boolean showInVirtualContainer); - - ItemPath getPath(); - - //NEW - - boolean isReadOnly(); - - void setReadOnly(boolean readOnly); - - ExpressionType getFormComponentValidator(); - - List getValues(); - VW getValue() throws SchemaException; - - boolean isStripe(); - void setStripe(boolean stripe); - - I getItem(); - - boolean isColumn(); - void setColumn(boolean column); - - > void applyDelta(D delta) throws SchemaException; - - > Collection getDelta() throws SchemaException; - - ItemStatus findObjectStatus(); - - , O extends ObjectType> OW findObjectWrapper(); - - ItemStatus getStatus(); -} +/* + * Copyright (c) 2010-2018 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.gui.api.prism; + +import java.io.Serializable; +import java.util.Collection; +import java.util.List; + +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; +import com.evolveum.midpoint.gui.impl.prism.PrismValueWrapper; +import com.evolveum.midpoint.prism.Item; +import com.evolveum.midpoint.prism.ItemDefinition; +import com.evolveum.midpoint.prism.PrismValue; +import com.evolveum.midpoint.prism.Revivable; +import com.evolveum.midpoint.prism.delta.ItemDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.util.DebugDumpable; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserInterfaceElementVisibilityType; + +/** + * @author katka + * + */ +public interface ItemWrapper, ID extends ItemDefinition, VW extends PrismValueWrapper> extends ItemDefinition, Revivable, DebugDumpable, Serializable { + + + String debugDump(int indent); + + void setVisibleOverwrite(UserInterfaceElementVisibilityType visible); + boolean isVisible(PrismContainerValueWrapper parentContainer, ItemVisibilityHandler visibilityHandler); + + boolean checkRequired(PageBase pageBase); + + PrismContainerValueWrapper getParent(); + + boolean isShowEmpty(); + + void setShowEmpty(boolean isShowEmpty, boolean recursive); + + boolean isShowInVirtualContainer(); + + void setShowInVirtualContainer(boolean showInVirtualContainer); + + ItemPath getPath(); + + //NEW + + boolean isReadOnly(); + + void setReadOnly(boolean readOnly); + + ExpressionType getFormComponentValidator(); + + List getValues(); + VW getValue() throws SchemaException; + + boolean isStripe(); + void setStripe(boolean stripe); + + I getItem(); + + boolean isColumn(); + void setColumn(boolean column); + + > void applyDelta(D delta) throws SchemaException; + + > Collection getDelta() throws SchemaException; + + ItemStatus findObjectStatus(); + + , O extends ObjectType> OW findObjectWrapper(); + + ItemStatus getStatus(); +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java index 6b0f295f6ad..24be4a53ff9 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/ObjectTabVisibleBehavior.java @@ -1,145 +1,112 @@ -/* - * Copyright (c) 2010-2018 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.gui.api.util; - -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.model.api.ModelInteractionService; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskManager; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.security.MidPointApplication; -import com.evolveum.midpoint.web.security.util.SecurityUtils; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.BooleanUtils; -import org.apache.commons.lang.ObjectUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.model.IModel; - -import javax.xml.namespace.QName; -import java.util.ArrayList; -import java.util.List; - -/** - * Created by Viliam Repan (lazyman). - */ -public class ObjectTabVisibleBehavior extends VisibleEnableBehaviour { - private static final long serialVersionUID = 1L; - - private static final String OPERATION_LOAD_GUI_CONFIGURATION = ObjectTabVisibleBehavior.class.getName() + ".loadGuiConfiguration"; - - private IModel> objectModel; - private String uiAuthorizationUrl; - private PageBase pageBase; - - public ObjectTabVisibleBehavior(IModel> objectModel, String uiAuthorizationUrl, PageBase pageBase) { - this.objectModel = objectModel; - this.uiAuthorizationUrl = uiAuthorizationUrl; - this.pageBase = pageBase; - } - - private ModelInteractionService getModelInteractionService() { - return ((MidPointApplication) MidPointApplication.get()).getModelInteractionService(); - } - - private TaskManager getTaskManager() { - return ((MidPointApplication) MidPointApplication.get()).getTaskManager(); - } - - @Override - public boolean isVisible() { - PrismObject object = objectModel.getObject(); - if (object == null) { - return true; - } - - Task task = WebModelServiceUtils.createSimpleTask(OPERATION_LOAD_GUI_CONFIGURATION, - SecurityUtils.getPrincipalUser().getFocus().asPrismObject(), getTaskManager()); - OperationResult result = task.getResult(); - - CompiledGuiProfile config; - try { - config = getModelInteractionService().getCompiledGuiProfile(task, result); - } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { - throw new SystemException("Cannot load GUI configuration: " + e.getMessage(), e); - } - - // find all object form definitions for specified type, if there is none we'll show all default tabs - List forms = findObjectForm(config, object); - if (forms.isEmpty()) { - return true; - } - - // we'll try to find includeDefault, if there is includeDefault=true, we can return true (all tabs visible) - for (ObjectFormType form : forms) { - if (BooleanUtils.isTrue(form.isIncludeDefaultForms())) { - return true; - } - } - - for (ObjectFormType form : forms) { - FormSpecificationType spec = form.getFormSpecification(); - if (spec == null || StringUtils.isEmpty(spec.getPanelUri())) { - continue; - } - - if (ObjectUtils.equals(uiAuthorizationUrl, spec.getPanelUri())) { - return true; - } - } - - return false; - } - - private List findObjectForm(CompiledGuiProfile config, PrismObject object) { - List result = new ArrayList<>(); - - if (config == null || config.getObjectForms() == null) { - return result; - } - - ObjectFormsType forms = config.getObjectForms(); - List list = forms.getObjectForm(); - if (list.isEmpty()) { - return result; - } - - for (ObjectFormType form : list) { - if (isApplicable(form, object)) { - result.add(form); - } - } - - return result; - } - - private boolean isApplicable(ObjectFormType form, PrismObject object) { - QName objectType = object.getDefinition().getTypeName(); - if (!objectType.equals(form.getType())) { - return false; - } - RoleRelationObjectSpecificationType roleRelation = form.getRoleRelation(); - if (roleRelation != null) { - List subjectRelations = roleRelation.getSubjectRelation(); - if (!pageBase.hasSubjectRoleRelation(object.getOid(), subjectRelations)) { - return false; - } - } - // TODO: roleRelation - return true; - } -} +/* + * Copyright (c) 2010-2018 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.gui.api.util; + +import java.util.ArrayList; +import java.util.List; +import javax.xml.namespace.QName; + +import org.apache.commons.lang.BooleanUtils; +import org.apache.commons.lang.ObjectUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.model.IModel; + +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +/** + * Created by Viliam Repan (lazyman). + */ +public class ObjectTabVisibleBehavior extends VisibleEnableBehaviour { + private static final long serialVersionUID = 1L; + + private IModel> objectModel; + private String uiAuthorizationUrl; + private PageBase pageBase; + + public ObjectTabVisibleBehavior(IModel> objectModel, String uiAuthorizationUrl, PageBase pageBase) { + this.objectModel = objectModel; + this.uiAuthorizationUrl = uiAuthorizationUrl; + this.pageBase = pageBase; + } + + @Override + public boolean isVisible() { + PrismObject object = objectModel.getObject(); + if (object == null) { + return true; + } + + CompiledGuiProfile config = pageBase.getCompiledGuiProfile(); + + // find all object form definitions for specified type, if there is none we'll show all default tabs + List forms = findObjectForm(config, object); + if (forms.isEmpty()) { + return true; + } + + // we'll try to find includeDefault, if there is includeDefault=true, we can return true (all tabs visible) + for (ObjectFormType form : forms) { + if (BooleanUtils.isTrue(form.isIncludeDefaultForms())) { + return true; + } + } + + for (ObjectFormType form : forms) { + FormSpecificationType spec = form.getFormSpecification(); + if (spec == null || StringUtils.isEmpty(spec.getPanelUri())) { + continue; + } + + if (ObjectUtils.equals(uiAuthorizationUrl, spec.getPanelUri())) { + return true; + } + } + + return false; + } + + private List findObjectForm(CompiledGuiProfile config, PrismObject object) { + List result = new ArrayList<>(); + + if (config == null || config.getObjectForms() == null) { + return result; + } + + ObjectFormsType forms = config.getObjectForms(); + List list = forms.getObjectForm(); + if (list.isEmpty()) { + return result; + } + + for (ObjectFormType form : list) { + if (isApplicable(form, object)) { + result.add(form); + } + } + + return result; + } + + private boolean isApplicable(ObjectFormType form, PrismObject object) { + QName objectType = object.getDefinition().getTypeName(); + if (!objectType.equals(form.getType())) { + return false; + } + RoleRelationObjectSpecificationType roleRelation = form.getRoleRelation(); + if (roleRelation != null) { + List subjectRelations = roleRelation.getSubjectRelation(); + return pageBase.hasSubjectRoleRelation(object.getOid(), subjectRelations); + } + // TODO: roleRelation + return true; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java index 204411310a6..ac1a9604b90 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/PrismObjectWrapperFactoryImpl.java @@ -1,302 +1,170 @@ -/* - * Copyright (c) 2010-2018 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.gui.impl.factory; - -import java.util.Collection; -import java.util.List; -import java.util.stream.Collectors; -import javax.annotation.PostConstruct; -import javax.xml.namespace.QName; - -import org.apache.commons.collections4.CollectionUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.ItemWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.registry.GuiComponentRegistry; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.impl.prism.*; -import com.evolveum.midpoint.model.api.ModelInteractionService; -import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.exception.*; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - -/** - * @author katka - */ -@Component -public class PrismObjectWrapperFactoryImpl extends PrismContainerWrapperFactoryImpl implements PrismObjectWrapperFactory { - - private static final Trace LOGGER = TraceManager.getTrace(PrismObjectWrapperFactoryImpl.class); - - private static final String DOT_CLASS = PrismObjectWrapperFactoryImpl.class.getName() + "."; - private static final String OPERATION_DETERMINE_VIRTUAL_CONTAINERS = DOT_CLASS + "determineVirtualContainers"; - - private static final QName VIRTUAL_CONTAINER_COMPLEX_TYPE = new QName("VirtualContainerType"); - private static final QName VIRTUAL_CONTAINER = new QName("virtualContainer"); - - @Autowired private GuiComponentRegistry registry; - @Autowired protected ModelInteractionService modelInteractionService; - - public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status, WrapperContext context) throws SchemaException { - - try { - applySecurityConstraints(object, context); - } catch (CommunicationException | ObjectNotFoundException | SecurityViolationException | ConfigurationException | ExpressionEvaluationException e) { - context.getResult().recordFatalError("Cannot create object wrapper for " + object + ". An error occurred: " + e.getMessage(), e); - throw new SchemaException(e.getMessage(), e); - } - if (context.getObjectStatus() == null) { - context.setObjectStatus(status); - } - - Collection virtualContainers = modelInteractionService.determineVirtualContainers(object, context.getTask(), context.getResult()); - context.setVirtualContainers(virtualContainers); - - PrismObjectWrapper objectWrapper = createObjectWrapper(object, status); - if (context.getReadOnly() != null) { - objectWrapper.setReadOnly(context.getReadOnly().booleanValue()); - } - context.setShowEmpty(ItemStatus.ADDED == status); - objectWrapper.setExpanded(true); - PrismContainerValueWrapper valueWrapper = createValueWrapper(objectWrapper, object.getValue(), ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context); - objectWrapper.getValues().add(valueWrapper); - - registry.registerWrapperPanel(object.getDefinition().getTypeName(), PrismContainerPanel.class); - return objectWrapper; - - } - - @Override - public PrismObjectValueWrapper createContainerValueWrapper(PrismContainerWrapper objectWrapper, PrismContainerValue objectValue, ValueStatus status, WrapperContext context) { - return new PrismObjectValueWrapperImpl((PrismObjectWrapper) objectWrapper, (PrismObjectValue) objectValue, status); - } - - public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status) { - return new PrismObjectWrapperImpl(object, status); - } - - @Override - public PrismContainerValueWrapper createValueWrapper(PrismContainerWrapper parent, PrismContainerValue value, ValueStatus status, WrapperContext context) throws SchemaException { - PrismContainerValueWrapper objectValueWrapper = super.createValueWrapper(parent, value, status, context); - - if (CollectionUtils.isEmpty(context.getVirtualContainers())) { - return objectValueWrapper; - } - - for (VirtualContainersSpecificationType virtualContainer : context.getVirtualContainers()) { - - MutableComplexTypeDefinition mCtd = getPrismContext().definitionFactory().createComplexTypeDefinition(VIRTUAL_CONTAINER_COMPLEX_TYPE); - DisplayType display = virtualContainer.getDisplay(); - - //TODO: support full polystring -> translations could be defined directly there. - mCtd.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); - mCtd.setHelp(WebComponentUtil.getOrigStringFromPoly(display.getHelp())); - mCtd.setRuntimeSchema(true); - - MutablePrismContainerDefinition def = getPrismContext().definitionFactory().createContainerDefinition(VIRTUAL_CONTAINER, mCtd); - def.setMaxOccurs(1); - def.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); - def.setDynamic(true); - - ItemWrapperFactory factory = getRegistry().findWrapperFactory(def); - if (factory == null) { - LOGGER.warn("Cannot find factory for {}. Skipping wrapper creation.", def); - continue; - } - - WrapperContext ctx = context.clone(); - ctx.setVirtualItemSpecification(virtualContainer.getItem()); - ItemWrapper iw = factory.createWrapper(objectValueWrapper, def, ctx); - - if (iw == null) { - continue; - } - ((List) objectValueWrapper.getItems()).add(iw); - - } - - return objectValueWrapper; - } - -// private List determineVirtualContainers(PrismObject object, WrapperContext context) { -// -// OperationResult result = context.getResult().createMinorSubresult(OPERATION_DETERMINE_VIRTUAL_CONTAINERS); -// if (AssignmentHolderType.class.isAssignableFrom(object.getCompileTimeClass())) { -// -// try { -// ArchetypePolicyType archetypePolicyType = modelInteractionService.determineArchetypePolicy((PrismObject) object, result); -// if (archetypePolicyType != null) { -// ArchetypeAdminGuiConfigurationType archetyAdminGui = archetypePolicyType.getAdminGuiConfiguration(); -// if (archetyAdminGui != null) { -// GuiObjectDetailsPageType guiDetails = archetyAdminGui.getObjectDetails(); -// if (guiDetails != null) { -// return guiDetails.getContainer(); -// } -// } -// } -// } catch (SchemaException | ConfigurationException e) { -// LOGGER.error("Cannot determine virtual containers for {}, reason: {}", object, e.getMessage(), e); -// result.recordPartialError("Cannot determine virtual containers for " + object + ", reason: " + e.getMessage(), e); -// return null; -// } -// -// } -// -// QName objectType = object.getDefinition().getTypeName(); -// try { -// CompiledGuiProfile userProfile = modelInteractionService.getCompiledGuiProfile(context.getTask(), context.getResult()); -// GuiObjectDetailsSetType objectDetailsSetType = userProfile.getObjectDetails(); -// if (objectDetailsSetType == null) { -// result.recordSuccess(); -// return null; -// } -// List detailsPages = objectDetailsSetType.getObjectDetailsPage(); -// for (GuiObjectDetailsPageType detailsPage : detailsPages) { -// if (objectType == null) { -// LOGGER.trace("Object type is not known, skipping considering custom details page settings."); -// continue; -// } -// if (detailsPage.getType() == null) { -// LOGGER.trace("Object type for details page {} not know, skipping considering custom details page settings.", detailsPage); -// continue; -// } -// -// if (QNameUtil.match(objectType, detailsPage.getType())) { -// result.recordSuccess(); -// return detailsPage.getContainer(); -// } -// } -// result.recordSuccess(); -// return null; -// } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { -// LOGGER.error("Cannot determine virtual containers for {}, reason: {}", objectType, e.getMessage(), e); -// result.recordPartialError("Cannot determine virtual containers for " + objectType + ", reason: " + e.getMessage(), e); -// return null; -// } -// -// } - - /** - * @param object apply security constraint to the object, update wrapper context with additional information, e.g. shadow related attributes, ... - */ - protected void applySecurityConstraints(PrismObject object, WrapperContext context) throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { - AuthorizationPhaseType phase = context.getAuthzPhase(); - Task task = context.getTask(); - OperationResult result = context.getResult(); - -// ObjectReferenceType archetypesToBeAdded = null; -// if (AssignmentHolderType.class.isAssignableFrom(object.getCompileTimeClass())) { -// archetypesToBeAdded = listArchetypes((PrismObject) object); -// if (archetypesToBeAdded != null) { -// applyArchetypes((PrismObject) object, archetypesToBeAdded); -// } -// } - - try { - PrismObjectDefinition objectDef = modelInteractionService.getEditObjectDefinition(object, phase, task, result); - object.applyDefinition(objectDef, true); - } catch (SchemaException | ConfigurationException | ObjectNotFoundException | ExpressionEvaluationException - | CommunicationException | SecurityViolationException e) { - throw e; - } -// finally { -// if (archetypesToBeAdded != null) { -// cleanupArchetypesToBeAdded((PrismObject) object, archetypesToBeAdded); -// } -// } - - } - - private void applyArchetypes(PrismObject object, ObjectReferenceType ref) throws SchemaException { - PrismReference archetypeRef = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF); - - if (archetypeRef == null) { - archetypeRef = object.findOrCreateReference(AssignmentHolderType.F_ARCHETYPE_REF); - } - - if (CollectionUtils.isNotEmpty(archetypeRef.getValues())) { - throw new SchemaException("Cannot apply new archetype to the object with already assigned archetype."); - } - - archetypeRef.getValues().add(ref.asReferenceValue()); - } - - private void cleanupArchetypesToBeAdded(PrismObject object, ObjectReferenceType ref) throws SchemaException { - //Now we expect thet object can have just one archetyperef, so if something was added, we just remove it. - - PrismReference archetype = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF); - if (archetype == null) { - return; - } - - if (archetype.getValues() != null && archetype.getValues().size() > 1) { - throw new SchemaException("More then one archetype ref found, but this is not supported."); - } - - object.removeReference(AssignmentHolderType.F_ARCHETYPE_REF); - } - - private ObjectReferenceType listArchetypes(PrismObject object) throws SchemaException { - PrismContainer assignmentContainer = object.findContainer(AssignmentHolderType.F_ASSIGNMENT); - Collection assignments = null; - if (assignmentContainer != null) { - assignments = assignmentContainer.getRealValues(); - } - - if (CollectionUtils.isEmpty(assignments)) { - return null; - } - - List archetypeAssignments = assignments.stream().filter(a -> a.getTargetRef() != null && QNameUtil.match(ArchetypeType.COMPLEX_TYPE, a.getTargetRef().getType())).collect(Collectors.toList()); - - if (archetypeAssignments.size() > 1) { - throw new SchemaException("More then one archetype assignment not supported."); - } - - if (CollectionUtils.isEmpty(archetypeAssignments)) { - return null; - } - - AssignmentType archetypeAssignment = archetypeAssignments.iterator().next(); - - PrismReference existingArchetypeRefs = object.findReference(AssignmentHolderType.F_ARCHETYPE_REF); - if (existingArchetypeRefs == null || CollectionUtils.isEmpty(existingArchetypeRefs.getRealValues())) { - return archetypeAssignment.getTargetRef(); - } - - return null; - - } - - @Override - public boolean match(ItemDefinition def) { - return def instanceof PrismObjectDefinition; - } - - @Override - @PostConstruct - public void register() { - registry.addToRegistry(this); - } - - @Override - public int getOrder() { - return 100; - } - -} +/* + * Copyright (c) 2010-2018 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.gui.impl.factory; + +import java.util.Collection; +import java.util.List; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import javax.xml.namespace.QName; + +import org.apache.commons.collections4.CollectionUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.ItemWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.registry.GuiComponentRegistry; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.impl.prism.*; +import com.evolveum.midpoint.model.api.ModelInteractionService; +import com.evolveum.midpoint.model.api.authentication.CompiledGuiProfile; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +/** + * @author katka + */ +@Component +public class PrismObjectWrapperFactoryImpl extends PrismContainerWrapperFactoryImpl implements PrismObjectWrapperFactory { + + private static final Trace LOGGER = TraceManager.getTrace(PrismObjectWrapperFactoryImpl.class); + + private static final String DOT_CLASS = PrismObjectWrapperFactoryImpl.class.getName() + "."; + + private static final QName VIRTUAL_CONTAINER_COMPLEX_TYPE = new QName("VirtualContainerType"); + private static final QName VIRTUAL_CONTAINER = new QName("virtualContainer"); + + @Autowired private GuiComponentRegistry registry; + @Autowired protected ModelInteractionService modelInteractionService; + + public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status, WrapperContext context) throws SchemaException { + + try { + applySecurityConstraints(object, context); + } catch (CommunicationException | ObjectNotFoundException | SecurityViolationException | ConfigurationException | ExpressionEvaluationException e) { + context.getResult().recordFatalError("Cannot create object wrapper for " + object + ". An error occurred: " + e.getMessage(), e); + throw new SchemaException(e.getMessage(), e); + } + if (context.getObjectStatus() == null) { + context.setObjectStatus(status); + } + + Collection virtualContainers = modelInteractionService.determineVirtualContainers(object, context.getTask(), context.getResult()); + context.setVirtualContainers(virtualContainers); + + PrismObjectWrapper objectWrapper = createObjectWrapper(object, status); + if (context.getReadOnly() != null) { + objectWrapper.setReadOnly(context.getReadOnly().booleanValue()); + } + context.setShowEmpty(ItemStatus.ADDED == status); + objectWrapper.setExpanded(true); + PrismContainerValueWrapper valueWrapper = createValueWrapper(objectWrapper, object.getValue(), ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context); + objectWrapper.getValues().add(valueWrapper); + + registry.registerWrapperPanel(object.getDefinition().getTypeName(), PrismContainerPanel.class); + return objectWrapper; + + } + + @Override + public PrismObjectValueWrapper createContainerValueWrapper(PrismContainerWrapper objectWrapper, PrismContainerValue objectValue, ValueStatus status, WrapperContext context) { + return new PrismObjectValueWrapperImpl((PrismObjectWrapper) objectWrapper, (PrismObjectValue) objectValue, status); + } + + public PrismObjectWrapper createObjectWrapper(PrismObject object, ItemStatus status) { + return new PrismObjectWrapperImpl(object, status); + } + + @Override + public PrismContainerValueWrapper createValueWrapper(PrismContainerWrapper parent, PrismContainerValue value, ValueStatus status, WrapperContext context) throws SchemaException { + PrismContainerValueWrapper objectValueWrapper = super.createValueWrapper(parent, value, status, context); + + if (CollectionUtils.isEmpty(context.getVirtualContainers())) { + return objectValueWrapper; + } + + for (VirtualContainersSpecificationType virtualContainer : context.getVirtualContainers()) { + + MutableComplexTypeDefinition mCtd = getPrismContext().definitionFactory().createComplexTypeDefinition(VIRTUAL_CONTAINER_COMPLEX_TYPE); + DisplayType display = virtualContainer.getDisplay(); + + //TODO: support full polystring -> translations could be defined directly there. + mCtd.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); + mCtd.setHelp(WebComponentUtil.getOrigStringFromPoly(display.getHelp())); + mCtd.setRuntimeSchema(true); + + MutablePrismContainerDefinition def = getPrismContext().definitionFactory().createContainerDefinition(VIRTUAL_CONTAINER, mCtd); + def.setMaxOccurs(1); + def.setDisplayName(WebComponentUtil.getOrigStringFromPoly(display.getLabel())); + def.setDynamic(true); + + ItemWrapperFactory factory = getRegistry().findWrapperFactory(def); + if (factory == null) { + LOGGER.warn("Cannot find factory for {}. Skipping wrapper creation.", def); + continue; + } + + WrapperContext ctx = context.clone(); + ctx.setVirtualItemSpecification(virtualContainer.getItem()); + ItemWrapper iw = factory.createWrapper(objectValueWrapper, def, ctx); + iw.setVisibleOverwrite(virtualContainer.getVisibility()); + + if (iw == null) { + continue; + } + ((List) objectValueWrapper.getItems()).add(iw); + + } + + return objectValueWrapper; + } + + /** + * @param object apply security constraint to the object, update wrapper context with additional information, e.g. shadow related attributes, ... + */ + protected void applySecurityConstraints(PrismObject object, WrapperContext context) throws CommunicationException, ObjectNotFoundException, SchemaException, SecurityViolationException, ConfigurationException, ExpressionEvaluationException { + AuthorizationPhaseType phase = context.getAuthzPhase(); + Task task = context.getTask(); + OperationResult result = context.getResult(); + + try { + PrismObjectDefinition objectDef = modelInteractionService.getEditObjectDefinition(object, phase, task, result); + object.applyDefinition(objectDef, true); + } catch (SchemaException | ConfigurationException | ObjectNotFoundException | ExpressionEvaluationException + | CommunicationException | SecurityViolationException e) { + throw e; + } + + } + + @Override + public boolean match(ItemDefinition def) { + return def instanceof PrismObjectDefinition; + } + + @Override + @PostConstruct + public void register() { + registry.addToRegistry(this); + } + + @Override + public int getOrder() { + return 100; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java index fbfc689f9bc..548f4c8fc76 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemWrapperImpl.java @@ -16,6 +16,8 @@ import javax.xml.namespace.QName; import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; @@ -38,11 +40,6 @@ import com.evolveum.midpoint.web.component.data.column.ColumnUtils; import com.evolveum.midpoint.web.component.prism.ItemVisibility; import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FormItemServerValidationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FormItemValidationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ItemRefinedDefinitionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; /** * @author katka @@ -76,6 +73,7 @@ public abstract class ItemWrapperImpl parent, I item, ItemStatus status) { Validate.notNull(item, "Item must not be null."); @@ -374,6 +372,11 @@ public void setShowInVirtualContainer(boolean showInVirtualContainer) { this.showInVirtualContainer = showInVirtualContainer; } + @Override + public void setVisibleOverwrite(UserInterfaceElementVisibilityType visibleOverwrite) { + this.visibleOverwrite = visibleOverwrite; + } + @Override public boolean isVisible(PrismContainerValueWrapper parentContainer, ItemVisibilityHandler visibilityHandler) { @@ -720,4 +723,8 @@ protected I getOldItem() { public boolean isIndexOnly() { return false; // todo } + + protected UserInterfaceElementVisibilityType getVisibleOverwrite() { + return visibleOverwrite; + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java index 80c90056ab9..8ce34d4807a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java @@ -270,16 +270,11 @@ public List> getNonContainers() { PrismObjectWrapper objectWrapper = getParent().findObjectWrapper(); if (objectWrapper == null) { - LOGGER.trace("No object wraper foung. Skipping virtual items."); + LOGGER.trace("No object wrapper found. Skipping virtual items."); return nonContainers; } for (VirtualContainerItemSpecificationType virtualItem : getVirtualItems()) { - if (objectWrapper == null) { - //should not happen, if happens it means something veeery strange happened - continue; - } - try { ItemPath virtualItemPath = getVirtualItemPath(virtualItem); ItemWrapper itemWrapper = objectWrapper.findItem(virtualItemPath, ItemWrapper.class); @@ -292,17 +287,20 @@ public List> getNonContainers() { continue; } - ((List)nonContainers).add(itemWrapper); + if (checkContainerInclusion(itemWrapper)) { + ((List)nonContainers).add(itemWrapper); + } } catch (SchemaException e) { LOGGER.error("Cannot find wrapper with path {}, error occured {}", virtualItem, e.getMessage(), e); } - - } - return nonContainers; } + public boolean checkContainerInclusion(ItemWrapper itemWrapper) { + return true; + } + private ItemPath getVirtualItemPath(VirtualContainerItemSpecificationType virtualItem) throws SchemaException { ItemPathType itemPathType = virtualItem.getPath(); if (itemPathType == null) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java index a86e55f455d..d20bb60c936 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerWrapperImpl.java @@ -25,6 +25,8 @@ import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.MetadataType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserInterfaceElementVisibilityType; + import org.apache.commons.collections4.CollectionUtils; import org.jetbrains.annotations.NotNull; @@ -347,6 +349,10 @@ protected ItemPath getDeltaPathForStatus(ItemStatus status) { @Override public boolean isVisible(PrismContainerValueWrapper parent, ItemVisibilityHandler visibilityHandler) { + if (isVirtual() && getVisibleOverwrite() != null && UserInterfaceElementVisibilityType.HIDDEN == getVisibleOverwrite()) { + return false; + } + if (getComplexTypeDefinition().getTypeName().equals(MetadataType.COMPLEX_TYPE)) { return (getParent() != null && getParent().isShowMetadata()); } @@ -354,11 +360,7 @@ public boolean isVisible(PrismContainerValueWrapper parent, ItemVisibilityHandle // pretend that object is always expanded. it is becasue all other containers are children of it // and it can influence visibility behavior on different tabs. boolean parentExpanded = parent instanceof PrismObjectValueWrapper ? true : parent.isExpanded(); - return isVisibleByVisibilityHandler(parentExpanded - - - - , visibilityHandler); + return isVisibleByVisibilityHandler(parentExpanded, visibilityHandler); } @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java index 3b9ba675584..843b265ba48 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectMainPanel.java @@ -1,320 +1,322 @@ -/* - * Copyright (c) 2015-2016 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.web.component.objectdetails; - -import java.util.List; - -import org.apache.commons.lang.Validate; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.security.api.AuthorizationConstants; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.AjaxButton; -import com.evolveum.midpoint.web.component.AjaxSubmitButton; -import com.evolveum.midpoint.web.component.TabbedPanel; -import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.configuration.PageDebugView; -import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsDto; -import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsPanel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -/** - * @author semancik - * - */ -public abstract class AbstractObjectMainPanel extends Panel { - private static final long serialVersionUID = 1L; - - public static final String PARAMETER_SELECTED_TAB = "tab"; - - private static final String ID_MAIN_FORM = "mainForm"; - public static final String ID_TAB_PANEL = "tabPanel"; - private static final String ID_EXECUTE_OPTIONS = "executeOptions"; - private static final String ID_BACK = "back"; - private static final String ID_SAVE = "save"; - private static final String ID_EDIT_XML = "editXml"; - private static final String ID_PREVIEW_CHANGES = "previewChanges"; - - private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectMainPanel.class); - - private Form mainForm; - - private LoadableModel> objectModel; - - private LoadableModel executeOptionsModel = new LoadableModel(false) { - private static final long serialVersionUID = 1L; - - @Override - protected ExecuteChangeOptionsDto load() { - return ExecuteChangeOptionsDto.createFromSystemConfiguration(); - } - }; - - public AbstractObjectMainPanel(String id, LoadableModel> objectModel, PageAdminObjectDetails parentPage) { - super(id, objectModel); - Validate.notNull(objectModel, "Null object model"); - this.objectModel = objectModel; - initLayout(parentPage); - } - - @Override - protected void onConfigure() { - super.onConfigure(); - - TabbedPanel tabbedPanel = (TabbedPanel) get(ID_MAIN_FORM + ":" + ID_TAB_PANEL); - WebComponentUtil.setSelectedTabFromPageParameters(tabbedPanel, getPage().getPageParameters(), - PARAMETER_SELECTED_TAB); - } - - public LoadableModel> getObjectModel() { - return objectModel; - } - - public PrismObjectWrapper getObjectWrapper() { - return objectModel.getObject(); - } - - public PrismObject getObject() { - return objectModel.getObject().getObject(); - } - - public Form getMainForm() { - return mainForm; - } - - private void initLayout(PageAdminObjectDetails parentPage) { - mainForm = new Form<>(ID_MAIN_FORM, true); - add(mainForm); - initLayoutTabs(parentPage); - initLayoutOptions(); - initLayoutButtons(parentPage); - } - - protected void initLayoutTabs(final PageAdminObjectDetails parentPage) { - List tabs = createTabs(parentPage); - TabbedPanel tabPanel = WebComponentUtil.createTabPanel(ID_TAB_PANEL, parentPage, tabs, null, - PARAMETER_SELECTED_TAB); - mainForm.add(tabPanel); - } - - protected abstract List createTabs(PageAdminObjectDetails parentPage); - - protected void initLayoutOptions() { - ExecuteChangeOptionsPanel optionsPanel = new ExecuteChangeOptionsPanel(ID_EXECUTE_OPTIONS, - executeOptionsModel, true, false); - optionsPanel.setOutputMarkupId(true); - optionsPanel.add(new VisibleEnableBehaviour() { - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible() { - return getOptionsPanelVisibility(); - } - - }); - mainForm.add(optionsPanel); - } - - protected void initLayoutButtons(PageAdminObjectDetails parentPage) { - initLayoutPreviewButton(parentPage); - initLayoutSaveButton(parentPage); - initLayoutBackButton(parentPage); - initLayoutEditXmlButton(parentPage); - } - - protected void initLayoutSaveButton(final PageAdminObjectDetails parentPage) { - AjaxSubmitButton saveButton = new AjaxSubmitButton(ID_SAVE, parentPage.createStringResource("pageAdminFocus.button.save")) { - private static final long serialVersionUID = 1L; - - @Override - protected void onSubmit(AjaxRequestTarget target) { - getDetailsPage().savePerformed(target); - } - - @Override - protected void onError(AjaxRequestTarget target) { - target.add(parentPage.getFeedbackPanel()); - } - }; - saveButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible() { - return !getObjectWrapper().isReadOnly() && - !getDetailsPage().isForcedPreview(); - } - - @Override - public boolean isEnabled() { - //in case user isn't allowed to modify focus data but has - // e.g. #assign authorization, Save button is disabled on page load. - // Save button becomes enabled just if some changes are made - // on the Assignments tab (in the use case with #assign authorization) -// PrismContainerDefinition def = getObjectWrapper().getDefinition(); - if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) - && !getObjectWrapper().canModify()){ - return areSavePreviewButtonsEnabled(); - } - return true; - } - }); - saveButton.setOutputMarkupId(true); - saveButton.setOutputMarkupPlaceholderTag(true); - mainForm.setDefaultButton(saveButton); - mainForm.add(saveButton); - } - - // TEMPORARY - protected void initLayoutPreviewButton(final PageAdminObjectDetails parentPage) { - AjaxSubmitButton previewButton = new AjaxSubmitButton(ID_PREVIEW_CHANGES, parentPage.createStringResource("pageAdminFocus.button.previewChanges")) { - private static final long serialVersionUID = 1L; - - @Override - protected void onSubmit(AjaxRequestTarget target) { - getDetailsPage().previewPerformed(target); - } - - @Override - protected void onError(AjaxRequestTarget target) { - target.add(parentPage.getFeedbackPanel()); - } - }; - previewButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return AbstractObjectMainPanel.this.isPreviewButtonVisible(); - } - - @Override - public boolean isEnabled() { -// PrismContainerDefinition def = getObjectWrapper().getDefinition(); - if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) - && !getObjectWrapper().canModify()){ - return areSavePreviewButtonsEnabled(); - } - return true; - } - }); - previewButton.setOutputMarkupId(true); - previewButton.setOutputMarkupPlaceholderTag(true); - mainForm.add(previewButton); - } - - protected boolean isPreviewButtonVisible(){ - return !getObjectWrapper().isReadOnly(); - } - - protected void initLayoutBackButton(PageAdminObjectDetails parentPage) { - AjaxButton back = new AjaxButton(ID_BACK, parentPage.createStringResource("pageAdminFocus.button.back")) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - backPerformed(target); - } - - }; - back.setOutputMarkupId(true); - back.setOutputMarkupPlaceholderTag(true); - mainForm.add(back); - } - - private void initLayoutEditXmlButton(final PageAdminObjectDetails parentPage){ - AjaxButton editXmlButton = new AjaxButton(ID_EDIT_XML, parentPage.createStringResource("AbstractObjectMainPanel.editXmlButton")) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - ConfirmationPanel confirmationPanel = new ConfirmationPanel(parentPage.getMainPopupBodyId(), - parentPage.createStringResource("AbstractObjectMainPanel.confirmEditXmlRedirect")){ - private static final long serialVersionUID = 1L; - - @Override - public void yesPerformed(AjaxRequestTarget target) { - PageParameters parameters = new PageParameters(); - parameters.add(PageDebugView.PARAM_OBJECT_ID, parentPage.getObjectWrapper().getOid()); - parameters.add(PageDebugView.PARAM_OBJECT_TYPE, parentPage.getCompileTimeClass().getSimpleName()); - parentPage.navigateToNext(PageDebugView.class, parameters); - } - - @Override - public StringResourceModel getTitle() { - return new StringResourceModel("pageUsers.message.confirmActionPopupTitle"); - } - }; - - parentPage.showMainPopup(confirmationPanel, target); - } - }; - editXmlButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_CONFIGURATION_URL, - AuthorizationConstants.AUTZ_UI_CONFIGURATION_DEBUG_URL) && - !getObjectWrapper().isReadOnly(); - } - }); - mainForm.add(editXmlButton); - - } - public ExecuteChangeOptionsDto getExecuteChangeOptionsDto() { - return executeOptionsModel.getObject(); - } - - private void backPerformed(AjaxRequestTarget target) { - getDetailsPage().redirectBack(); - } - - protected PageAdminObjectDetails getDetailsPage() { - return (PageAdminObjectDetails)getPage(); - } - - protected boolean getOptionsPanelVisibility(){ - if (getObjectWrapper().isReadOnly()){ - return false; - } -// PrismContainerDefinition def = getObjectWrapper().getDefinition(); - if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) - && !getObjectWrapper().canModify()){ - return false; - } - return true; - } - - public void reloadSavePreviewButtons(AjaxRequestTarget target){ - target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_PREVIEW_CHANGES)); - target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_SAVE)); - - } - - protected boolean areSavePreviewButtonsEnabled() { - return false; - } - - public TabbedPanel getTabbedPanel() { - return (TabbedPanel) get(WebComponentUtil.getPageBase(this).createComponentPath(ID_MAIN_FORM, ID_TAB_PANEL)); - } -} +/* + * Copyright (c) 2015-2016 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.web.component.objectdetails; + +import java.util.List; + +import org.apache.commons.lang.Validate; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.security.api.AuthorizationConstants; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.AjaxSubmitButton; +import com.evolveum.midpoint.web.component.TabbedPanel; +import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.web.page.admin.configuration.PageDebugView; +import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsDto; +import com.evolveum.midpoint.web.page.admin.users.component.ExecuteChangeOptionsPanel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; + +/** + * @author semancik + * + */ +public abstract class AbstractObjectMainPanel extends Panel { + private static final long serialVersionUID = 1L; + + public static final String PARAMETER_SELECTED_TAB = "tab"; + + private static final String ID_MAIN_FORM = "mainForm"; + public static final String ID_TAB_PANEL = "tabPanel"; + private static final String ID_EXECUTE_OPTIONS = "executeOptions"; + private static final String ID_BACK = "back"; + private static final String ID_SAVE = "save"; + private static final String ID_EDIT_XML = "editXml"; + private static final String ID_PREVIEW_CHANGES = "previewChanges"; + + //private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectMainPanel.class); + + private Form> mainForm; + + private LoadableModel> objectModel; + //get rid of it. + private PageAdminObjectDetails parentPage; + + private LoadableModel executeOptionsModel = new LoadableModel(false) { + private static final long serialVersionUID = 1L; + + @Override + protected ExecuteChangeOptionsDto load() { + return ExecuteChangeOptionsDto.createFromSystemConfiguration(); + } + }; + + public AbstractObjectMainPanel(String id, LoadableModel> objectModel, PageAdminObjectDetails parentPage) { + super(id, objectModel); + Validate.notNull(objectModel, "Null object model"); + this.objectModel = objectModel; + this.parentPage = parentPage; + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(parentPage); + } + + @Override + protected void onConfigure() { + super.onConfigure(); + + TabbedPanel tabbedPanel = (TabbedPanel) get(ID_MAIN_FORM + ":" + ID_TAB_PANEL); + WebComponentUtil.setSelectedTabFromPageParameters(tabbedPanel, getPage().getPageParameters(), + PARAMETER_SELECTED_TAB); + } + + public LoadableModel> getObjectModel() { + return objectModel; + } + + public PrismObjectWrapper getObjectWrapper() { + return objectModel.getObject(); + } + + public PrismObject getObject() { + return objectModel.getObject().getObject(); + } + + public Form> getMainForm() { + return mainForm; + } + + private void initLayout(PageAdminObjectDetails parentPage) { + mainForm = new Form<>(ID_MAIN_FORM, true); + add(mainForm); + initLayoutTabs(parentPage); + initLayoutOptions(); + initLayoutButtons(parentPage); + } + + protected void initLayoutTabs(final PageAdminObjectDetails parentPage) { + List tabs = createTabs(parentPage); + TabbedPanel tabPanel = WebComponentUtil.createTabPanel(ID_TAB_PANEL, parentPage, tabs, null, PARAMETER_SELECTED_TAB); + mainForm.add(tabPanel); + } + + protected abstract List createTabs(PageAdminObjectDetails parentPage); + + protected void initLayoutOptions() { + ExecuteChangeOptionsPanel optionsPanel = new ExecuteChangeOptionsPanel(ID_EXECUTE_OPTIONS, + executeOptionsModel, true, false); + optionsPanel.setOutputMarkupId(true); + optionsPanel.add(new VisibleEnableBehaviour() { + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return getOptionsPanelVisibility(); + } + + }); + mainForm.add(optionsPanel); + } + + protected void initLayoutButtons(PageAdminObjectDetails parentPage) { + initLayoutPreviewButton(parentPage); + initLayoutSaveButton(parentPage); + initLayoutBackButton(parentPage); + initLayoutEditXmlButton(parentPage); + } + + protected void initLayoutSaveButton(final PageAdminObjectDetails parentPage) { + AjaxSubmitButton saveButton = new AjaxSubmitButton(ID_SAVE, parentPage.createStringResource("pageAdminFocus.button.save")) { + private static final long serialVersionUID = 1L; + + @Override + protected void onSubmit(AjaxRequestTarget target) { + getDetailsPage().savePerformed(target); + } + + @Override + protected void onError(AjaxRequestTarget target) { + target.add(parentPage.getFeedbackPanel()); + } + }; + saveButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return !getObjectWrapper().isReadOnly() && + !getDetailsPage().isForcedPreview(); + } + + @Override + public boolean isEnabled() { + //in case user isn't allowed to modify focus data but has + // e.g. #assign authorization, Save button is disabled on page load. + // Save button becomes enabled just if some changes are made + // on the Assignments tab (in the use case with #assign authorization) +// PrismContainerDefinition def = getObjectWrapper().getDefinition(); + if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) + && !getObjectWrapper().canModify()){ + return areSavePreviewButtonsEnabled(); + } + return true; + } + }); + saveButton.setOutputMarkupId(true); + saveButton.setOutputMarkupPlaceholderTag(true); + mainForm.setDefaultButton(saveButton); + mainForm.add(saveButton); + } + + // TEMPORARY + protected void initLayoutPreviewButton(final PageAdminObjectDetails parentPage) { + AjaxSubmitButton previewButton = new AjaxSubmitButton(ID_PREVIEW_CHANGES, parentPage.createStringResource("pageAdminFocus.button.previewChanges")) { + private static final long serialVersionUID = 1L; + + @Override + protected void onSubmit(AjaxRequestTarget target) { + getDetailsPage().previewPerformed(target); + } + + @Override + protected void onError(AjaxRequestTarget target) { + target.add(parentPage.getFeedbackPanel()); + } + }; + previewButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return AbstractObjectMainPanel.this.isPreviewButtonVisible(); + } + + @Override + public boolean isEnabled() { +// PrismContainerDefinition def = getObjectWrapper().getDefinition(); + if (ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) + && !getObjectWrapper().canModify()){ + return areSavePreviewButtonsEnabled(); + } + return true; + } + }); + previewButton.setOutputMarkupId(true); + previewButton.setOutputMarkupPlaceholderTag(true); + mainForm.add(previewButton); + } + + protected boolean isPreviewButtonVisible(){ + return !getObjectWrapper().isReadOnly(); + } + + protected void initLayoutBackButton(PageAdminObjectDetails parentPage) { + AjaxButton back = new AjaxButton(ID_BACK, parentPage.createStringResource("pageAdminFocus.button.back")) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + backPerformed(); + } + + }; + back.setOutputMarkupId(true); + back.setOutputMarkupPlaceholderTag(true); + mainForm.add(back); + } + + private void initLayoutEditXmlButton(final PageAdminObjectDetails parentPage){ + AjaxButton editXmlButton = new AjaxButton(ID_EDIT_XML, parentPage.createStringResource("AbstractObjectMainPanel.editXmlButton")) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + ConfirmationPanel confirmationPanel = new ConfirmationPanel(parentPage.getMainPopupBodyId(), + parentPage.createStringResource("AbstractObjectMainPanel.confirmEditXmlRedirect")){ + private static final long serialVersionUID = 1L; + + @Override + public void yesPerformed(AjaxRequestTarget target) { + PageParameters parameters = new PageParameters(); + parameters.add(PageDebugView.PARAM_OBJECT_ID, parentPage.getObjectWrapper().getOid()); + parameters.add(PageDebugView.PARAM_OBJECT_TYPE, parentPage.getCompileTimeClass().getSimpleName()); + parentPage.navigateToNext(PageDebugView.class, parameters); + } + + @Override + public StringResourceModel getTitle() { + return new StringResourceModel("pageUsers.message.confirmActionPopupTitle"); + } + }; + + parentPage.showMainPopup(confirmationPanel, target); + } + }; + editXmlButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return WebComponentUtil.isAuthorized(AuthorizationConstants.AUTZ_UI_CONFIGURATION_URL, + AuthorizationConstants.AUTZ_UI_CONFIGURATION_DEBUG_URL) && + !getObjectWrapper().isReadOnly(); + } + }); + mainForm.add(editXmlButton); + + } + public ExecuteChangeOptionsDto getExecuteChangeOptionsDto() { + return executeOptionsModel.getObject(); + } + + private void backPerformed() { + getDetailsPage().redirectBack(); + } + + @SuppressWarnings("unchecked") + protected PageAdminObjectDetails getDetailsPage() { + return (PageAdminObjectDetails) getPage(); + } + + protected boolean getOptionsPanelVisibility(){ + if (getObjectWrapper().isReadOnly()){ + return false; + } + return ItemStatus.NOT_CHANGED != getObjectWrapper().getStatus() + || getObjectWrapper().canModify(); + } + + public void reloadSavePreviewButtons(AjaxRequestTarget target){ + target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_PREVIEW_CHANGES)); + target.add(AbstractObjectMainPanel.this.get(ID_MAIN_FORM).get(ID_SAVE)); + + } + + protected boolean areSavePreviewButtonsEnabled() { + return false; + } + + public TabbedPanel getTabbedPanel() { + return (TabbedPanel) get(WebComponentUtil.getPageBase(this).createComponentPath(ID_MAIN_FORM, ID_TAB_PANEL)); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java index 48f35fc34e8..ee97d1f6e5d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractObjectTabPanel.java @@ -1,149 +1,126 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import javax.xml.namespace.QName; - -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettings; -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.MarkupContainer; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.StringResourceModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.impl.prism.PrismPropertyPanel; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.dialog.Popupable; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.prism.ItemVisibility; -import com.evolveum.midpoint.web.model.PrismPropertyWrapperModel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; - -/** - * @author semancik - */ -public abstract class AbstractObjectTabPanel extends Panel { - private static final long serialVersionUID = 1L; - - protected static final String ID_MAIN_FORM = "mainForm"; - - private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectTabPanel.class); - - private LoadableModel> objectWrapperModel; -// protected PageBase pageBase; - private Form> mainForm; - - public AbstractObjectTabPanel(String id, Form> mainForm, LoadableModel> objectWrapperModel) { - super(id); - this.objectWrapperModel = objectWrapperModel; - this.mainForm = mainForm; -// this.pageBase = pageBase; - } - - public LoadableModel> getObjectWrapperModel() { - return objectWrapperModel; - } - - public PrismObjectWrapper getObjectWrapper() { - return objectWrapperModel.getObject(); - } - - protected PrismContext getPrismContext() { - return getPageBase().getPrismContext(); - } - - protected PageParameters getPageParameters() { - return getPageBase().getPageParameters(); - } - - public PageBase getPageBase() { - return (PageBase) getPage(); - } - - public Form> getMainForm() { - return mainForm; - } - - public StringResourceModel createStringResource(String resourceKey, Object... objects) { - return PageBase.createStringResourceStatic(this, resourceKey, objects); -// return new StringResourceModel(resourceKey, this, null, resourceKey, objects); - } - - public String getString(String resourceKey, Object... objects) { - return createStringResource(resourceKey, objects).getString(); - } - - protected String createComponentPath(String... components) { - return StringUtils.join(components, ":"); - } - - protected void showResult(OperationResult result) { - getPageBase().showResult(result); - } - - protected void showResult(OperationResult result, boolean showSuccess) { - getPageBase().showResult(result, false); - } - - - protected WebMarkupContainer getFeedbackPanel() { - return getPageBase().getFeedbackPanel(); - } - - public Object findParam(String param, String oid, OperationResult result) { - - Object object = null; - - //TODO: FIXME get(PARAM_OID) returns collection - for (OperationResult subResult : result.getSubresults()) { - if (subResult != null && subResult.getParams() != null) { - if (subResult.getParams().get(param) != null - && subResult.getParams().get(OperationResult.PARAM_OID) != null - && subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) { - return subResult.getParams().get(param); - } - object = findParam(param, oid, subResult); - - } - } - return object; - } - - protected void showModalWindow(Popupable popupable, AjaxRequestTarget target) { - getPageBase().showMainPopup(popupable, target); - target.add(getFeedbackPanel()); - } - - protected Panel addPrismPropertyPanel(MarkupContainer parentComponent, String id, QName typeName, ItemPath propertyPath) { - - try { - //FIXME : really always visible? - ItemPanelSettingsBuilder settingsBuilder = new ItemPanelSettingsBuilder(); - settingsBuilder.visibilityHandler(wrapper -> ItemVisibility.VISIBLE); - - Panel panel = getPageBase().initItemPanel(id, typeName, PrismPropertyWrapperModel.fromContainerWrapper(getObjectWrapperModel(), propertyPath), settingsBuilder.build()); - parentComponent.add(panel); - return panel; - } catch (SchemaException e) { - LOGGER.error("Cannot create panel for {}", typeName, e); - getSession().error("Cannot create panel for " + typeName + ", reason: " + e.getMessage()); - } - - return null; - } -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import javax.xml.namespace.QName; + +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.MarkupContainer; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.StringResourceModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.dialog.Popupable; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.prism.ItemVisibility; +import com.evolveum.midpoint.web.model.PrismPropertyWrapperModel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; + +/** + * @author semancik + */ +public abstract class AbstractObjectTabPanel extends Panel { + private static final long serialVersionUID = 1L; + + protected static final String ID_MAIN_FORM = "mainForm"; + + private static final Trace LOGGER = TraceManager.getTrace(AbstractObjectTabPanel.class); + + private LoadableModel> objectWrapperModel; + private Form> mainForm; + + public AbstractObjectTabPanel(String id, Form> mainForm, LoadableModel> objectWrapperModel) { + super(id); + this.objectWrapperModel = objectWrapperModel; + this.mainForm = mainForm; + } + + public LoadableModel> getObjectWrapperModel() { + return objectWrapperModel; + } + + public PrismObjectWrapper getObjectWrapper() { + return objectWrapperModel.getObject(); + } + + protected PrismContext getPrismContext() { + return getPageBase().getPrismContext(); + } + + protected PageParameters getPageParameters() { + return getPageBase().getPageParameters(); + } + + public PageBase getPageBase() { + return (PageBase) getPage(); + } + + public Form> getMainForm() { + return mainForm; + } + + public StringResourceModel createStringResource(String resourceKey, Object... objects) { + return PageBase.createStringResourceStatic(this, resourceKey, objects); +// return new StringResourceModel(resourceKey, this, null, resourceKey, objects); + } + + public String getString(String resourceKey, Object... objects) { + return createStringResource(resourceKey, objects).getString(); + } + + protected String createComponentPath(String... components) { + return StringUtils.join(components, ":"); + } + + protected void showResult(OperationResult result) { + getPageBase().showResult(result); + } + + protected void showResult(OperationResult result, boolean showSuccess) { + getPageBase().showResult(result, showSuccess); + } + + + protected WebMarkupContainer getFeedbackPanel() { + return getPageBase().getFeedbackPanel(); + } + + protected void showModalWindow(Popupable popupable, AjaxRequestTarget target) { + getPageBase().showMainPopup(popupable, target); + target.add(getFeedbackPanel()); + } + + protected Panel addPrismPropertyPanel(MarkupContainer parentComponent, String id, QName typeName, ItemPath propertyPath) { + + try { + //FIXME : really always visible? + ItemPanelSettingsBuilder settingsBuilder = new ItemPanelSettingsBuilder(); + settingsBuilder.visibilityHandler(wrapper -> ItemVisibility.VISIBLE); + + Panel panel = getPageBase().initItemPanel(id, typeName, PrismPropertyWrapperModel.fromContainerWrapper(getObjectWrapperModel(), propertyPath), settingsBuilder.build()); + parentComponent.add(panel); + return panel; + } catch (SchemaException e) { + LOGGER.error("Cannot create panel for {}", typeName, e); + getSession().error("Cannot create panel for " + typeName + ", reason: " + e.getMessage()); + } + + return null; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java index 4a26cd7b5cd..b18ede050d8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AbstractRoleMainPanel.java @@ -1,327 +1,326 @@ -/* - * Copyright (c) 2015-2016 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.web.component.objectdetails; - -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -import org.apache.wicket.ajax.AjaxChannel; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.Model; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.LoggingUtils; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.AjaxButton; -import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; -import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; -import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.web.page.admin.PageAdminFocus; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; -import com.evolveum.midpoint.web.page.admin.roles.AvailableRelationDto; -import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; -import com.evolveum.midpoint.web.page.self.PageAssignmentShoppingCart; -import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; -import com.evolveum.midpoint.web.session.RoleCatalogStorage; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AreaCategoryType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ServiceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -/** - * @author semancik - * - */ -public abstract class AbstractRoleMainPanel extends FocusMainPanel { - private static final long serialVersionUID = 1L; - - private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMainPanel.class); - - private static final String DOT_CLASS = AbstractRoleMainPanel.class.getName(); - private static final String OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM = DOT_CLASS + "canSearchRoleMembershipItem"; - private static final String OPERATION_LOAD_ASSIGNMENTS_LIMIT = DOT_CLASS + "loadAssignmentsLimit"; - private static final String ID_SHOPPING_CART_BUTTONS_PANEL = "shoppingCartButtonsPanel"; - private static final String ID_ADD_TO_CART_BUTTON = "addToCartButton"; - - public AbstractRoleMainPanel(String id, LoadableModel> objectModel, - LoadableModel> projectionModel, - PageAdminFocus parentPage) { - super(id, objectModel, projectionModel, parentPage); - } - - @Override - protected void initLayoutButtons(PageAdminObjectDetails parentPage) { - super.initLayoutButtons(parentPage); - initShoppingCartPanel(parentPage); - } - - private void initShoppingCartPanel(PageAdminObjectDetails parentPage){ - RoleCatalogStorage storage = parentPage.getSessionStorage().getRoleCatalog(); - - WebMarkupContainer shoppingCartButtonsPanel = new WebMarkupContainer(ID_SHOPPING_CART_BUTTONS_PANEL); - shoppingCartButtonsPanel.setOutputMarkupId(true); - shoppingCartButtonsPanel.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - //show panel only in case if user came to object details from - // Role Catalog page - return PageAssignmentShoppingCart.class.equals(WebComponentUtil.getPreviousPageClass(parentPage)); - } - }); - getMainForm().add(shoppingCartButtonsPanel); - - AjaxButton addToCartButton = new AjaxButton(ID_ADD_TO_CART_BUTTON, parentPage - .createStringResource("PageAssignmentDetails.addToCartButton")) { - private static final long serialVersionUID = 1L; - - @Override - protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { - attributes.setChannel(new AjaxChannel("blocking", AjaxChannel.Type.ACTIVE)); - } - - @Override - public void onClick(AjaxRequestTarget target) { - AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(getObject().asObjectable(), UserDtoStatus.ADD, parentPage); - storage.getAssignmentShoppingCart().add(dto); - parentPage.redirectBack(); - } - }; - addToCartButton.add(AttributeAppender.append("class", new LoadableModel() { - @Override - protected String load() { - return addToCartButton.isEnabled() ? "btn btn-success" : "btn btn-success disabled"; - } - })); - addToCartButton.setOutputMarkupId(true); - addToCartButton.add(new VisibleEnableBehaviour(){ - private static final long serialVersionUID = 1L; - - @Override - public boolean isEnabled(){ - int assignmentsLimit = AssignmentsUtil.loadAssignmentsLimit(new OperationResult(OPERATION_LOAD_ASSIGNMENTS_LIMIT), - parentPage); - AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(AbstractRoleMainPanel.this.getObject().asObjectable(), - UserDtoStatus.ADD, parentPage); - return !AssignmentsUtil.isShoppingCartAssignmentsLimitReached(assignmentsLimit, parentPage) - && (storage.isMultiUserRequest() || dto.isAssignable()); } - }); - addToCartButton.add(AttributeAppender.append("title", - AssignmentsUtil.getShoppingCartAssignmentsLimitReachedTitleModel(parentPage))); - shoppingCartButtonsPanel.add(addToCartButton); - } - - @Override - protected List createTabs(final PageAdminObjectDetails parentPage) { - List tabs = super.createTabs(parentPage); - - tabs.add( - new PanelTab(parentPage.createStringResource("pageAdminFocus.applicablePolicies"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_APPLICABLE_POLICIES_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusApplicablePoliciesTabPanel<>(panelId, getMainForm(), getObjectModel()); - } - }); - - tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.inducement"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_INDUCEMENTS_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - SwitchAssignmentTypePanel panel = new SwitchAssignmentTypePanel(panelId, - PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), AbstractRoleType.F_INDUCEMENT)){ - private static final long serialVersionUID = 1L; - - @Override - protected boolean isInducement(){ - return true; - } - }; - return panel; -// return new AbstractRoleInducementPanel<>(panelId, getMainForm(), getObjectModel(), parentPage); - } - - @Override - public String getCount(){ - return getInducementsCount(); - } - - }); - - tabs.add(new PanelTab(parentPage.createStringResource("pageRole.members"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_MEMBERS_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createMemberPanel(panelId); - } - - @Override - public boolean isVisible() { - return super.isVisible() && - getObjectWrapper().getStatus() != ItemStatus.ADDED && - isAllowedToReadRoleMembership(getObjectWrapper().getOid(), parentPage); - } - }); - - tabs.add(new PanelTab(parentPage.createStringResource("pageRole.governance"), - getTabVisibility( ComponentConstants.UI_FOCUS_TAB_GOVERNANCE_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createGovernancePanel(panelId); - } - - @Override - public boolean isVisible() { - return super.isVisible() && getObjectWrapper().getStatus() != ItemStatus.ADDED; - } - }); - - return tabs; - } - - - public AbstractRoleMemberPanel createMemberPanel(String panelId) { - - return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { - - private static final long serialVersionUID = 1L; - - @Override - protected AvailableRelationDto getSupportedRelations() { - return getSupportedMembersTabRelations(); - } - - }; - } - - - public AbstractRoleMemberPanel createGovernancePanel(String panelId) { - - return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { - - private static final long serialVersionUID = 1L; - - @Override - protected AvailableRelationDto getSupportedRelations() { - AvailableRelationDto avariableRelations = getSupportedGovernanceTabRelations(); - avariableRelations.setDefaultRelation(getDefaultGovernanceRelation()); - return avariableRelations; - } - - @Override - protected Map getAuthorizations(QName complexType) { - return getGovernanceTabAuthorizations(); - } - - }; - } - - protected AvailableRelationDto getSupportedMembersTabRelations(){ - List relations = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.ADMINISTRATION, getDetailsPage()); - List governance = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage()); - governance.forEach(r -> relations.remove(r)); - return new AvailableRelationDto(relations); - } - - protected AvailableRelationDto getSupportedGovernanceTabRelations(){ - return new AvailableRelationDto(WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage())); - } - - protected QName getDefaultGovernanceRelation(){ - return WebComponentUtil.getCategoryDefaultRelation(AreaCategoryType.GOVERNANCE); - } - - protected Map getGovernanceTabAuthorizations(){ - return GuiAuthorizationConstants.GOVERNANCE_MEMBERS_AUTHORIZATIONS; - } - - private boolean isAllowedToReadRoleMembership(String abstractRoleOid, PageBase parentPage){ - return isAllowedToReadRoleMembershipItemForType(abstractRoleOid, UserType.class, parentPage) - || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, RoleType.class, parentPage) - || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, OrgType.class, parentPage) - || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, ServiceType.class, parentPage); - } - - private boolean isAllowedToReadRoleMembershipItemForType(String abstractRoleOid, Class type, PageBase parentPage){ - ObjectQuery query = parentPage.getPrismContext().queryFor(type) - .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(abstractRoleOid).build(); - Task task = parentPage.createSimpleTask(OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM); - OperationResult result = task.getResult(); - boolean isAllowed = false; - try { - isAllowed = parentPage.getModelInteractionService() - .canSearch(type, null, null, false, query, task, result); - } catch (Exception ex){ - LoggingUtils.logUnexpectedException(LOGGER, "Couldn't check if user is allowed to search for roleMembershipRef item", ex); - } - return isAllowed; - } - - private String getInducementsCount(){ - PrismObject focus = getObjectModel().getObject().getObject(); - List inducements = focus.asObjectable().getInducement(); - if (inducements == null){ - return ""; - } - return Integer.toString(inducements.size()); - } - - - //TODO what? why? when? - @Override - protected boolean areSavePreviewButtonsEnabled(){ - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismContainerWrapper assignmentsWrapper; - try { - assignmentsWrapper = focusWrapper.findContainer(AbstractRoleType.F_INDUCEMENT); - } catch (SchemaException e) { - return false; - } - return super.areSavePreviewButtonsEnabled() || isAssignmentsModelChanged(assignmentsWrapper); - } -} +/* + * Copyright (c) 2015-2016 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.web.component.objectdetails; + +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import org.apache.wicket.ajax.AjaxChannel; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.attributes.AjaxRequestAttributes; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.Model; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; +import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; +import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.web.page.admin.PageAdminFocus; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; +import com.evolveum.midpoint.web.page.admin.roles.AvailableRelationDto; +import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; +import com.evolveum.midpoint.web.page.self.PageAssignmentShoppingCart; +import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; +import com.evolveum.midpoint.web.session.RoleCatalogStorage; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AreaCategoryType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ServiceType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; + +/** + * @author semancik + * + */ +public abstract class AbstractRoleMainPanel extends FocusMainPanel { + private static final long serialVersionUID = 1L; + + private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMainPanel.class); + + private static final String DOT_CLASS = AbstractRoleMainPanel.class.getName(); + private static final String OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM = DOT_CLASS + "canSearchRoleMembershipItem"; + private static final String OPERATION_LOAD_ASSIGNMENTS_LIMIT = DOT_CLASS + "loadAssignmentsLimit"; + private static final String ID_SHOPPING_CART_BUTTONS_PANEL = "shoppingCartButtonsPanel"; + private static final String ID_ADD_TO_CART_BUTTON = "addToCartButton"; + + public AbstractRoleMainPanel(String id, LoadableModel> objectModel, + LoadableModel> projectionModel, + PageAdminFocus parentPage) { + super(id, objectModel, projectionModel, parentPage); + } + + @Override + protected void initLayoutButtons(PageAdminObjectDetails parentPage) { + super.initLayoutButtons(parentPage); + initShoppingCartPanel(parentPage); + } + + private void initShoppingCartPanel(PageAdminObjectDetails parentPage){ + RoleCatalogStorage storage = parentPage.getSessionStorage().getRoleCatalog(); + + WebMarkupContainer shoppingCartButtonsPanel = new WebMarkupContainer(ID_SHOPPING_CART_BUTTONS_PANEL); + shoppingCartButtonsPanel.setOutputMarkupId(true); + shoppingCartButtonsPanel.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + //show panel only in case if user came to object details from + // Role Catalog page + return PageAssignmentShoppingCart.class.equals(WebComponentUtil.getPreviousPageClass(parentPage)); + } + }); + getMainForm().add(shoppingCartButtonsPanel); + + AjaxButton addToCartButton = new AjaxButton(ID_ADD_TO_CART_BUTTON, parentPage + .createStringResource("PageAssignmentDetails.addToCartButton")) { + private static final long serialVersionUID = 1L; + + @Override + protected void updateAjaxAttributes(AjaxRequestAttributes attributes) { + attributes.setChannel(new AjaxChannel("blocking", AjaxChannel.Type.ACTIVE)); + } + + @Override + public void onClick(AjaxRequestTarget target) { + AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(getObject().asObjectable(), UserDtoStatus.ADD, parentPage); + storage.getAssignmentShoppingCart().add(dto); + parentPage.redirectBack(); + } + }; + addToCartButton.add(AttributeAppender.append("class", new LoadableModel() { + @Override + protected String load() { + return addToCartButton.isEnabled() ? "btn btn-success" : "btn btn-success disabled"; + } + })); + addToCartButton.setOutputMarkupId(true); + addToCartButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isEnabled(){ + int assignmentsLimit = AssignmentsUtil.loadAssignmentsLimit(new OperationResult(OPERATION_LOAD_ASSIGNMENTS_LIMIT), + parentPage); + AssignmentEditorDto dto = AssignmentEditorDto.createDtoFromObject(AbstractRoleMainPanel.this.getObject().asObjectable(), + UserDtoStatus.ADD, parentPage); + return !AssignmentsUtil.isShoppingCartAssignmentsLimitReached(assignmentsLimit, parentPage) + && (storage.isMultiUserRequest() || dto.isAssignable()); } + }); + addToCartButton.add(AttributeAppender.append("title", + AssignmentsUtil.getShoppingCartAssignmentsLimitReachedTitleModel(parentPage))); + shoppingCartButtonsPanel.add(addToCartButton); + } + + @Override + protected List createTabs(final PageAdminObjectDetails parentPage) { + List tabs = super.createTabs(parentPage); + + tabs.add( + new PanelTab(parentPage.createStringResource("pageAdminFocus.applicablePolicies"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_APPLICABLE_POLICIES_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusApplicablePoliciesTabPanel<>(panelId, getMainForm(), getObjectModel()); + } + }); + + tabs.add(new CountablePanelTab(parentPage.createStringResource("FocusType.inducement"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_INDUCEMENTS_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + SwitchAssignmentTypePanel panel = new SwitchAssignmentTypePanel(panelId, + PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), AbstractRoleType.F_INDUCEMENT)){ + private static final long serialVersionUID = 1L; + + @Override + protected boolean isInducement(){ + return true; + } + }; + return panel; + } + + @Override + public String getCount(){ + return getInducementsCount(); + } + + }); + + tabs.add(new PanelTab(parentPage.createStringResource("pageRole.members"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_MEMBERS_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createMemberPanel(panelId); + } + + @Override + public boolean isVisible() { + return super.isVisible() && + getObjectWrapper().getStatus() != ItemStatus.ADDED && + isAllowedToReadRoleMembership(getObjectWrapper().getOid(), parentPage); + } + }); + + tabs.add(new PanelTab(parentPage.createStringResource("pageRole.governance"), + getTabVisibility( ComponentConstants.UI_FOCUS_TAB_GOVERNANCE_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createGovernancePanel(panelId); + } + + @Override + public boolean isVisible() { + return super.isVisible() && getObjectWrapper().getStatus() != ItemStatus.ADDED; + } + }); + + return tabs; + } + + + public AbstractRoleMemberPanel createMemberPanel(String panelId) { + + return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { + + private static final long serialVersionUID = 1L; + + @Override + protected AvailableRelationDto getSupportedRelations() { + return getSupportedMembersTabRelations(); + } + + }; + } + + + public AbstractRoleMemberPanel createGovernancePanel(String panelId) { + + return new AbstractRoleMemberPanel(panelId, new Model<>(getObject().asObjectable())) { + + private static final long serialVersionUID = 1L; + + @Override + protected AvailableRelationDto getSupportedRelations() { + AvailableRelationDto avariableRelations = getSupportedGovernanceTabRelations(); + avariableRelations.setDefaultRelation(getDefaultGovernanceRelation()); + return avariableRelations; + } + + @Override + protected Map getAuthorizations(QName complexType) { + return getGovernanceTabAuthorizations(); + } + + }; + } + + protected AvailableRelationDto getSupportedMembersTabRelations(){ + List relations = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.ADMINISTRATION, getDetailsPage()); + List governance = WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage()); + governance.forEach(r -> relations.remove(r)); + return new AvailableRelationDto(relations); + } + + protected AvailableRelationDto getSupportedGovernanceTabRelations(){ + return new AvailableRelationDto(WebComponentUtil.getCategoryRelationChoices(AreaCategoryType.GOVERNANCE, getDetailsPage())); + } + + protected QName getDefaultGovernanceRelation(){ + return WebComponentUtil.getCategoryDefaultRelation(AreaCategoryType.GOVERNANCE); + } + + protected Map getGovernanceTabAuthorizations(){ + return GuiAuthorizationConstants.GOVERNANCE_MEMBERS_AUTHORIZATIONS; + } + + private boolean isAllowedToReadRoleMembership(String abstractRoleOid, PageBase parentPage){ + return isAllowedToReadRoleMembershipItemForType(abstractRoleOid, UserType.class, parentPage) + || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, RoleType.class, parentPage) + || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, OrgType.class, parentPage) + || isAllowedToReadRoleMembershipItemForType(abstractRoleOid, ServiceType.class, parentPage); + } + + private boolean isAllowedToReadRoleMembershipItemForType(String abstractRoleOid, Class type, PageBase parentPage){ + ObjectQuery query = parentPage.getPrismContext().queryFor(type) + .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(abstractRoleOid).build(); + Task task = parentPage.createSimpleTask(OPERATION_CAN_SEARCH_ROLE_MEMBERSHIP_ITEM); + OperationResult result = task.getResult(); + boolean isAllowed = false; + try { + isAllowed = parentPage.getModelInteractionService() + .canSearch(type, null, null, false, query, task, result); + } catch (Exception ex){ + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't check if user is allowed to search for roleMembershipRef item", ex); + } + return isAllowed; + } + + private String getInducementsCount(){ + PrismObject focus = getObjectModel().getObject().getObject(); + List inducements = focus.asObjectable().getInducement(); + if (inducements == null){ + return ""; + } + return Integer.toString(inducements.size()); + } + + + //TODO what? why? when? + @Override + protected boolean areSavePreviewButtonsEnabled(){ + PrismObjectWrapper focusWrapper = getObjectModel().getObject(); + PrismContainerWrapper assignmentsWrapper; + try { + assignmentsWrapper = focusWrapper.findContainer(AbstractRoleType.F_INDUCEMENT); + } catch (SchemaException e) { + return false; + } + return super.areSavePreviewButtonsEnabled() || isAssignmentsModelChanged(assignmentsWrapper); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java index c8b488437f8..3d0abcc8a31 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeAssignmentsTabPanel.java @@ -1,67 +1,65 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.component.objectdetails; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.Model; - -/** - * @author semancik - */ -public class AssignmentHolderTypeAssignmentsTabPanel extends AbstractObjectTabPanel { - private static final long serialVersionUID = 1L; - - private static final String ID_ASSIGNMENTS = "assignmentsContainer"; - private static final String ID_ASSIGNMENTS_PANEL = "assignmentsPanel"; - private static final String DOT_CLASS = AssignmentHolderTypeAssignmentsTabPanel.class.getName() + "."; - - public AssignmentHolderTypeAssignmentsTabPanel(String id, Form mainForm, LoadableModel> focusWrapperModel, PageBase page) { - super(id, mainForm, focusWrapperModel); - - } - - @Override - protected void onInitialize() { - super.onInitialize(); - initLayout(); - } - - private void initLayout() { - WebMarkupContainer assignments = new WebMarkupContainer(ID_ASSIGNMENTS); - assignments.setOutputMarkupId(true); - add(assignments); - PrismContainerWrapperModel model = PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), AssignmentHolderType.F_ASSIGNMENT); - SwitchAssignmentTypePanel panel = createPanel(ID_ASSIGNMENTS_PANEL, model); - - assignments.add(panel); - } - - protected SwitchAssignmentTypePanel createPanel(String panelId, PrismContainerWrapperModel model) { - SwitchAssignmentTypePanel panel = new SwitchAssignmentTypePanel(panelId, model != null ? model : Model.of()){ - private static final long serialVersionUID = 1L; - - @Override - protected boolean isReadonly(){ - return AssignmentHolderTypeAssignmentsTabPanel.this.isReadonly(); - } - }; - return panel; - } - - protected boolean isReadonly(){ - return false; - } - -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.component.objectdetails; + +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.Model; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.web.component.assignment.SwitchAssignmentTypePanel; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; + +/** + * @author semancik + */ +public class AssignmentHolderTypeAssignmentsTabPanel extends AbstractObjectTabPanel { + private static final long serialVersionUID = 1L; + + private static final String ID_ASSIGNMENTS = "assignmentsContainer"; + private static final String ID_ASSIGNMENTS_PANEL = "assignmentsPanel"; + + public AssignmentHolderTypeAssignmentsTabPanel(String id, Form> mainForm, LoadableModel> focusWrapperModel) { + super(id, mainForm, focusWrapperModel); + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + private void initLayout() { + WebMarkupContainer assignments = new WebMarkupContainer(ID_ASSIGNMENTS); + assignments.setOutputMarkupId(true); + add(assignments); + PrismContainerWrapperModel model = PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), AssignmentHolderType.F_ASSIGNMENT); + SwitchAssignmentTypePanel panel = createPanel(ID_ASSIGNMENTS_PANEL, model); + + assignments.add(panel); + } + + protected SwitchAssignmentTypePanel createPanel(String panelId, PrismContainerWrapperModel model) { + return new SwitchAssignmentTypePanel(panelId, model != null ? model : Model.of()){ + private static final long serialVersionUID = 1L; + + @Override + protected boolean isReadonly(){ + return AssignmentHolderTypeAssignmentsTabPanel.this.isReadonly(); + } + }; + } + + protected boolean isReadonly(){ + return false; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java index 2ea5ed7a45d..7754500543f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeDetailsTabPanel.java @@ -1,86 +1,72 @@ -/* - * Copyright (c) 2010-2018 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.web.component.objectdetails; - -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.prism.ItemVisibility; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.wicket.markup.html.panel.Panel; - -import java.util.ArrayList; -import java.util.List; - -/** - * @author semancik - */ -public class AssignmentHolderTypeDetailsTabPanel extends AbstractObjectTabPanel { - private static final long serialVersionUID = 1L; - - protected static final String ID_FOCUS_FORM = "focusDetails"; - - private static final String ID_MAIN_PANEL = "main"; - private static final String ID_ACTIVATION_PANEL = "activation"; - private static final String ID_PASSWORD_PANEL = "password"; - - private static final Trace LOGGER = TraceManager.getTrace(AssignmentHolderTypeDetailsTabPanel.class); - - public AssignmentHolderTypeDetailsTabPanel(String id, Form mainForm, - LoadableModel> focusWrapperModel) { - super(id, mainForm, focusWrapperModel); - - } - - @Override - protected void onInitialize() { - super.onInitialize(); - initLayout(); - } - - private void initLayout() { - - try { - - ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder().visibilityHandler(w -> ItemVisibility.AUTO).showOnTopLevel(true); - builder.headerVisibility(false); - - Panel main = getPageBase().initItemPanel(ID_MAIN_PANEL, getObjectWrapper().getTypeName(), - PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.EMPTY_PATH), builder.build()); - add(main); - Panel activation = getPageBase().initItemPanel(ID_ACTIVATION_PANEL, ActivationType.COMPLEX_TYPE, - PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), FocusType.F_ACTIVATION), builder.build()); - add(activation); - Panel password = getPageBase().initItemPanel(ID_PASSWORD_PANEL, PasswordType.COMPLEX_TYPE, - PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD)), builder.build()); - add(password); - } catch (SchemaException e) { - LOGGER.error("Could not create focus details panel. Reason: {}", e.getMessage(), e); - } - } - - private List getVisibleContainers() { - List paths = new ArrayList<>(); - paths.add(ItemPath.EMPTY_PATH); - paths.add(SchemaConstants.PATH_ACTIVATION); - paths.add(SchemaConstants.PATH_PASSWORD); - if (WebModelServiceUtils.isEnableExperimentalFeature(getPageBase())) { - paths.add(AbstractRoleType.F_DATA_PROTECTION); - } - return paths; - } - - -} +/* + * Copyright (c) 2010-2018 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.web.component.objectdetails; + +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.prism.ItemVisibility; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.wicket.markup.html.panel.Panel; + +import java.util.ArrayList; +import java.util.List; + +/** + * @author semancik + */ +public class AssignmentHolderTypeDetailsTabPanel extends AbstractObjectTabPanel { + private static final long serialVersionUID = 1L; + + private static final String ID_MAIN_PANEL = "main"; + private static final String ID_ACTIVATION_PANEL = "activation"; + private static final String ID_PASSWORD_PANEL = "password"; + + private static final Trace LOGGER = TraceManager.getTrace(AssignmentHolderTypeDetailsTabPanel.class); + + public AssignmentHolderTypeDetailsTabPanel(String id, Form mainForm, + LoadableModel> focusWrapperModel) { + super(id, mainForm, focusWrapperModel); + + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + private void initLayout() { + + try { + + ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder().visibilityHandler(w -> ItemVisibility.AUTO).showOnTopLevel(true); + builder.headerVisibility(false); + + Panel main = getPageBase().initItemPanel(ID_MAIN_PANEL, getObjectWrapper().getTypeName(), + PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.EMPTY_PATH), builder.build()); + add(main); + Panel activation = getPageBase().initItemPanel(ID_ACTIVATION_PANEL, ActivationType.COMPLEX_TYPE, + PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), FocusType.F_ACTIVATION), builder.build()); + add(activation); + Panel password = getPageBase().initItemPanel(ID_PASSWORD_PANEL, PasswordType.COMPLEX_TYPE, + PrismContainerWrapperModel.fromContainerWrapper(getObjectWrapperModel(), ItemPath.create(UserType.F_CREDENTIALS, CredentialsType.F_PASSWORD)), builder.build()); + add(password); + } catch (SchemaException e) { + LOGGER.error("Could not create focus details panel. Reason: {}", e.getMessage(), e); + } + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java index 0cd6c754bd6..a7275e022ec 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/AssignmentHolderTypeMainPanel.java @@ -1,126 +1,118 @@ -/* - * Copyright (c) 2015-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.web.component.objectdetails; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; -import com.evolveum.midpoint.gui.api.util.HistoryPageTabVisibleBehavior; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.IModel; - -import java.util.ArrayList; -import java.util.List; - - -/** - * Created by honchar - */ -public class AssignmentHolderTypeMainPanel extends AbstractObjectMainPanel{ - private static final long serialVersionUID = 1L; - - private AssignmentHolderTypeAssignmentsTabPanel assignmentsTabPanel = null; - - public AssignmentHolderTypeMainPanel(String id, LoadableModel> objectModel, - PageAdminObjectDetails parentPage) { - super(id, objectModel, parentPage); - } - - @Override - protected List createTabs(final PageAdminObjectDetails parentPage) { - List tabs = new ArrayList<>(); - - tabs.add( - new PanelTab(parentPage.createStringResource("pageAdminFocus.basic"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_BASIC_URL, true, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new AssignmentHolderTypeDetailsTabPanel<>(panelId, getMainForm(), getObjectModel()); - } - }); - - tabs.add( - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.assignments"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_ASSIGNMENTS_URL, true, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new AssignmentHolderTypeAssignmentsTabPanel(panelId, getMainForm(), getObjectModel(), parentPage){ - private static final long serialVersionUID = 1L; - - @Override - protected boolean isReadonly(){ - return AssignmentHolderTypeMainPanel.this.isReadonly(); - } - }; - } - - @Override - public String getCount() { - return Integer.toString(countAssignments()); - } - }); - - return tabs; - } - - protected IModel> unwrapModel() { - return new IModel>() { - - @Override - public PrismObject getObject() { - return getObjectWrapper().getObject(); - } - }; - } - - protected ObjectTabVisibleBehavior getTabVisibility(String authUrl, boolean isVisibleOnHistoryPage, PageAdminObjectDetails parentPage){ - if (isFocusHistoryPage()){ - return new HistoryPageTabVisibleBehavior(unwrapModel(), authUrl, isVisibleOnHistoryPage, parentPage); - } else { - return new ObjectTabVisibleBehavior(unwrapModel(), authUrl, parentPage); - } - } - - protected boolean isFocusHistoryPage(){ - return false; - } - - protected int countAssignments() { - int rv = 0; - PrismObject focus = getObjectModel().getObject().getObject(); - List assignments = focus.asObjectable().getAssignment(); - for (AssignmentType assignment : assignments) { - if (!AssignmentsUtil.isConsentAssignment(assignment) - && AssignmentsUtil.isAssignmentRelevant(assignment) && !AssignmentsUtil.isArchetypeAssignment(assignment)) { - rv++; - } - } - return rv; - } - - //this value will be used independently of object wrapper isReadonly value, - protected boolean isReadonly(){ - return false; - } - - -} +/* + * Copyright (c) 2015-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.web.component.objectdetails; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; +import com.evolveum.midpoint.gui.api.util.HistoryPageTabVisibleBehavior; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentHolderType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.IModel; + +import java.util.ArrayList; +import java.util.List; + + +/** + * Created by honchar + */ +public class AssignmentHolderTypeMainPanel extends AbstractObjectMainPanel{ + private static final long serialVersionUID = 1L; + + public AssignmentHolderTypeMainPanel(String id, LoadableModel> objectModel, + PageAdminObjectDetails parentPage) { + super(id, objectModel, parentPage); + } + + @Override + protected List createTabs(final PageAdminObjectDetails parentPage) { + List tabs = new ArrayList<>(); + + tabs.add( + new PanelTab(parentPage.createStringResource("pageAdminFocus.basic"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_BASIC_URL, true, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new AssignmentHolderTypeDetailsTabPanel<>(panelId, getMainForm(), getObjectModel()); + } + }); + + tabs.add( + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.assignments"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_ASSIGNMENTS_URL, true, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new AssignmentHolderTypeAssignmentsTabPanel(panelId, getMainForm(), getObjectModel()){ + private static final long serialVersionUID = 1L; + + @Override + protected boolean isReadonly(){ + return AssignmentHolderTypeMainPanel.this.isReadonly(); + } + }; + } + + @Override + public String getCount() { + return Integer.toString(countAssignments()); + } + }); + + return tabs; + } + + protected IModel> unwrapModel() { + return (IModel>) () -> getObjectWrapper().getObject(); + } + + protected ObjectTabVisibleBehavior getTabVisibility(String authUrl, boolean isVisibleOnHistoryPage, PageAdminObjectDetails parentPage){ + if (isFocusHistoryPage()){ + return new HistoryPageTabVisibleBehavior<>(unwrapModel(), authUrl, isVisibleOnHistoryPage, parentPage); + } else { + return new ObjectTabVisibleBehavior<>(unwrapModel(), authUrl, parentPage); + } + } + + protected boolean isFocusHistoryPage(){ + return false; + } + + protected int countAssignments() { + int rv = 0; + PrismObject focus = getObjectModel().getObject().getObject(); + List assignments = focus.asObjectable().getAssignment(); + for (AssignmentType assignment : assignments) { + if (!AssignmentsUtil.isConsentAssignment(assignment) + && AssignmentsUtil.isAssignmentRelevant(assignment) && !AssignmentsUtil.isArchetypeAssignment(assignment)) { + rv++; + } + } + return rv; + } + + //this value will be used independently of object wrapper isReadonly value, + protected boolean isReadonly(){ + return false; + } + + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java index 4b367e16e6e..bc3d844da5a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/FocusMainPanel.java @@ -1,334 +1,296 @@ -/* - * Copyright (c) 2015-2018 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.web.component.objectdetails; - -import java.lang.reflect.Constructor; -import java.lang.reflect.InvocationTargetException; -import java.util.List; - -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.wf.util.QueryUtils; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.lang.StringUtils; -import org.apache.commons.lang.Validate; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.IModel; -import org.apache.wicket.util.string.StringValue; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; -import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; -import com.evolveum.midpoint.model.api.ModelAuthorizationAction; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.form.Form; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; - -/** - * @author semancik - * - */ -public class FocusMainPanel extends AssignmentHolderTypeMainPanel { - - private static final long serialVersionUID = 1L; - - private static final Trace LOGGER = TraceManager.getTrace(FocusMainPanel.class); - - private LoadableModel> projectionModel; - - public FocusMainPanel(String id, LoadableModel> objectModel, - LoadableModel> projectionModel, - PageAdminObjectDetails parentPage) { - super(id, objectModel, parentPage); - Validate.notNull(projectionModel, "Null projection model"); - this.projectionModel = projectionModel; - initLayout(parentPage); - } - - private void initLayout(final PageAdminObjectDetails parentPage) { - getMainForm().setMultiPart(true); - - } - - @Override - protected void onInitialize() { - super.onInitialize(); - StringValue oidValue = getPage().getPageParameters().get(OnePageParameterEncoder.PARAMETER); - - } - - private ObjectQuery createTaskQuery(String oid, PageBase page) { - if (oid == null) { - oid = "non-existent"; // TODO !!!!!!!!!!!!!!!!!!!! - } - return page.getPrismContext().queryFor(CaseType.class) - .item(CaseType.F_OBJECT_REF).ref(oid) - .and() - .item(CaseType.F_ARCHETYPE_REF) - .ref(SystemObjectsType.ARCHETYPE_OPERATION_REQUEST.value()) - .and() - .not() - .item(CaseType.F_STATE) - .eq(SchemaConstants.CASE_STATE_CLOSED) - .desc(ItemPath.create(CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP)) - .build(); - } - - @Override - protected List createTabs(final PageAdminObjectDetails parentPage) { - List tabs = super.createTabs(parentPage); - - List objectFormTypes = parentPage.getObjectFormTypes(); - // default tabs are always added to component structure, visibility is decided later in - // visible behavior based on adminGuiConfiguration - addDefaultTabs(parentPage, tabs); - addSpecificTabs(parentPage, tabs); - if (objectFormTypes == null) { - return tabs; - } - - for (ObjectFormType objectFormType : objectFormTypes) { - final FormSpecificationType formSpecificationType = objectFormType.getFormSpecification(); - if (formSpecificationType == null){ - continue; - } - String title = formSpecificationType.getTitle(); - if (title == null) { - title = "pageAdminFocus.extended"; - } - - if (StringUtils.isEmpty(formSpecificationType.getPanelClass())) { - continue; - } - - tabs.add( - new PanelTab(parentPage.createStringResource(title)) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createTabPanel(panelId, formSpecificationType, parentPage); - } - }); - } - - return tabs; - } - - protected WebMarkupContainer createTabPanel(String panelId, FormSpecificationType formSpecificationType, - PageAdminObjectDetails parentPage) { - String panelClassName = formSpecificationType.getPanelClass(); - - Class panelClass; - try { - panelClass = Class.forName(panelClassName); - } catch (ClassNotFoundException e) { - throw new SystemException("Panel class '"+panelClassName+"' as specified in admin GUI configuration was not found", e); - } - if (AbstractFocusTabPanel.class.isAssignableFrom(panelClass)) { - Constructor constructor; - try { - constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class, LoadableModel.class); - } catch (NoSuchMethodException | SecurityException e) { - throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,LoadableModel,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); - } - AbstractFocusTabPanel tabPanel; - try { - tabPanel = (AbstractFocusTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel(), projectionModel); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); - } - return tabPanel; - } else if (AbstractObjectTabPanel.class.isAssignableFrom(panelClass)) { - Constructor constructor; - try { - constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class); - } catch (NoSuchMethodException | SecurityException e) { - throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); - } - AbstractObjectTabPanel tabPanel; - try { - tabPanel = (AbstractObjectTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel()); - } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { - throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); - } - return tabPanel; - - } else { - throw new UnsupportedOperationException("Tab panels that are not subclasses of AbstractObjectTabPanel or AbstractFocusTabPanel are not supported yet (got "+panelClass+")"); - } - } - - protected WebMarkupContainer createFocusDetailsTabPanel(String panelId, PageAdminObjectDetails parentPage) { - return new AssignmentHolderTypeDetailsTabPanel(panelId, getMainForm(), getObjectModel()); - } - - protected WebMarkupContainer createFocusProjectionsTabPanel(String panelId, PageAdminObjectDetails parentPage) { - return new FocusProjectionsTabPanel<>(panelId, getMainForm(), getObjectModel(), projectionModel); - } - - protected WebMarkupContainer createObjectHistoryTabPanel(String panelId, PageAdminObjectDetails parentPage) { - return new ObjectHistoryTabPanel(panelId, getMainForm(), getObjectModel()){ - protected void currentStateButtonClicked(AjaxRequestTarget target, PrismObject object, String date){ - viewObjectHistoricalDataPerformed(target, object, date); - } - }; - } - - protected void viewObjectHistoricalDataPerformed(AjaxRequestTarget target, PrismObject object, String date){ - } - - protected IModel> unwrapModel() { - return new IModel>() { - - @Override - public PrismObject getObject() { - return getObjectWrapper().getObject(); - } - }; - } - - protected void addSpecificTabs(final PageAdminObjectDetails parentPage, List tabs) { - } - - private void addDefaultTabs(final PageAdminObjectDetails parentPage, List tabs) { - - tabs.add(1, - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.projections"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_PROJECTIONS_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createFocusProjectionsTabPanel(panelId, parentPage); - } - - @Override - public String getCount() { - return Integer.toString(projectionModel.getObject() == null ? 0 : projectionModel.getObject().size()); - } - }); - - if (WebComponentUtil.isAuthorized(ModelAuthorizationAction.AUDIT_READ.getUrl()) && getObjectWrapper().getStatus() != ItemStatus.ADDED){ - tabs.add( - new PanelTab(parentPage.createStringResource("pageAdminFocus.objectHistory"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_OBJECT_HISTORY_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return createObjectHistoryTabPanel(panelId, parentPage); - } - }); - } - - tabs.add( - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.cases"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusTasksTabPanel(panelId, getMainForm(), getObjectModel(), - countFocusObjectTasks(parentPage) > 0); - } - - @Override - public String getCount() { - return Integer.toString(countFocusObjectTasks(parentPage)); - } - }); - - tabs.add( - new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.triggers"), - getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new FocusTriggersTabPanel(panelId, getMainForm(), getObjectModel()); - } - - @Override - public String getCount() { - return Integer.toString(countFocusObjectTriggers()); - } - }); - - } - - private int countFocusObjectTasks(PageBase parentPage){ - String oid = null; - if (getObjectWrapper() == null || StringUtils.isEmpty(getObjectWrapper().getOid())) { - oid = "non-existent"; - } else { - oid = getObjectWrapper().getOid(); - } - ObjectQuery casesQuery = QueryUtils.filterForCasesOverUser(parentPage.getPrismContext().queryFor(CaseType.class), oid) - .desc(ItemPath.create(CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP)) - .build(); - return WebModelServiceUtils.countObjects(CaseType.class, casesQuery, parentPage); - } - - private int countFocusObjectTriggers(){ - PrismObjectWrapper objectWrapper = getObjectWrapper(); - if (objectWrapper.getObject() != null){ - F focusObject = objectWrapper.getObject().asObjectable(); - return focusObject.getTrigger() != null ? focusObject.getTrigger().size() : 0; - } - return 0; - } - - @Override - @Deprecated - protected boolean areSavePreviewButtonsEnabled() { - PrismObjectWrapper focusWrapper = getObjectModel().getObject(); - PrismContainerWrapper assignmentsWrapper; - try { - assignmentsWrapper = focusWrapper.findContainer(FocusType.F_ASSIGNMENT); - } catch (SchemaException e) { - LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); - return false; - } - return isAssignmentsModelChanged(assignmentsWrapper); - } - - protected boolean isAssignmentsModelChanged(PrismContainerWrapper assignmentsWrapper){ - if (assignmentsWrapper != null) { - for (PrismContainerValueWrapper assignmentWrapper : assignmentsWrapper.getValues()) { - if (ValueStatus.DELETED.equals(assignmentWrapper.getStatus()) || - ValueStatus.ADDED.equals(assignmentWrapper.getStatus())) { - return true; - } - } - } - return false; - } - -} +/* + * Copyright (c) 2015-2018 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.web.component.objectdetails; + +import java.lang.reflect.Constructor; +import java.lang.reflect.InvocationTargetException; +import java.util.List; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.lang.Validate; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.IModel; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.prism.ShadowWrapper; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; +import com.evolveum.midpoint.model.api.ModelAuthorizationAction; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SystemException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.form.Form; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.wf.util.QueryUtils; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +/** + * @author semancik + * + */ +public class FocusMainPanel extends AssignmentHolderTypeMainPanel { + + private static final long serialVersionUID = 1L; + + private static final Trace LOGGER = TraceManager.getTrace(FocusMainPanel.class); + + private LoadableModel> projectionModel; + + public FocusMainPanel(String id, LoadableModel> objectModel, + LoadableModel> projectionModel, + PageAdminObjectDetails parentPage) { + super(id, objectModel, parentPage); + Validate.notNull(projectionModel, "Null projection model"); + this.projectionModel = projectionModel; + } + + @Override + protected void onInitialize() { + super.onInitialize(); + + getMainForm().setMultiPart(true); + } + + @Override + protected List createTabs(final PageAdminObjectDetails parentPage) { + List tabs = super.createTabs(parentPage); + + List objectFormTypes = parentPage.getObjectFormTypes(); + // default tabs are always added to component structure, visibility is decided later in + // visible behavior based on adminGuiConfiguration + addDefaultTabs(parentPage, tabs); + addSpecificTabs(parentPage, tabs); + if (objectFormTypes == null) { + return tabs; + } + + for (ObjectFormType objectFormType : objectFormTypes) { + final FormSpecificationType formSpecificationType = objectFormType.getFormSpecification(); + if (formSpecificationType == null){ + continue; + } + String title = formSpecificationType.getTitle(); + if (title == null) { + title = "pageAdminFocus.extended"; + } + + if (StringUtils.isEmpty(formSpecificationType.getPanelClass())) { + continue; + } + + tabs.add( + new PanelTab(parentPage.createStringResource(title)) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createTabPanel(panelId, formSpecificationType); + } + }); + } + + return tabs; + } + + protected WebMarkupContainer createTabPanel(String panelId, FormSpecificationType formSpecificationType) { + String panelClassName = formSpecificationType.getPanelClass(); + + Class panelClass; + try { + panelClass = Class.forName(panelClassName); + } catch (ClassNotFoundException e) { + throw new SystemException("Panel class '"+panelClassName+"' as specified in admin GUI configuration was not found", e); + } + if (AbstractFocusTabPanel.class.isAssignableFrom(panelClass)) { + Constructor constructor; + try { + constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class, LoadableModel.class); + } catch (NoSuchMethodException | SecurityException e) { + throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,LoadableModel,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); + } + AbstractFocusTabPanel tabPanel; + try { + tabPanel = (AbstractFocusTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel(), projectionModel); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); + } + return tabPanel; + } else if (AbstractObjectTabPanel.class.isAssignableFrom(panelClass)) { + Constructor constructor; + try { + constructor = panelClass.getConstructor(String.class, Form.class, LoadableModel.class); + } catch (NoSuchMethodException | SecurityException e) { + throw new SystemException("Unable to locate constructor (String,Form,LoadableModel,PageBase) in "+panelClass+": "+e.getMessage(), e); + } + AbstractObjectTabPanel tabPanel; + try { + tabPanel = (AbstractObjectTabPanel) constructor.newInstance(panelId, getMainForm(), getObjectModel()); + } catch (InstantiationException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e) { + throw new SystemException("Error instantiating "+panelClass+": "+e.getMessage(), e); + } + return tabPanel; + + } else { + throw new UnsupportedOperationException("Tab panels that are not subclasses of AbstractObjectTabPanel or AbstractFocusTabPanel are not supported yet (got "+panelClass+")"); + } + } + + protected WebMarkupContainer createFocusProjectionsTabPanel(String panelId) { + return new FocusProjectionsTabPanel<>(panelId, getMainForm(), getObjectModel(), projectionModel); + } + + protected WebMarkupContainer createObjectHistoryTabPanel(String panelId) { + return new ObjectHistoryTabPanel(panelId, getMainForm(), getObjectModel()){ + protected void currentStateButtonClicked(AjaxRequestTarget target, PrismObject object, String date){ + viewObjectHistoricalDataPerformed(target, object, date); + } + }; + } + + protected void viewObjectHistoricalDataPerformed(AjaxRequestTarget target, PrismObject object, String date){ + } + + protected IModel> unwrapModel() { + return (IModel>) () -> getObjectWrapper().getObject(); + } + + protected void addSpecificTabs(final PageAdminObjectDetails parentPage, List tabs) { + } + + private void addDefaultTabs(final PageAdminObjectDetails parentPage, List tabs) { + + tabs.add(1, + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.projections"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_PROJECTIONS_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createFocusProjectionsTabPanel(panelId); + } + + @Override + public String getCount() { + return Integer.toString(projectionModel.getObject() == null ? 0 : projectionModel.getObject().size()); + } + }); + + if (WebComponentUtil.isAuthorized(ModelAuthorizationAction.AUDIT_READ.getUrl()) && getObjectWrapper().getStatus() != ItemStatus.ADDED){ + tabs.add( + new PanelTab(parentPage.createStringResource("pageAdminFocus.objectHistory"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_OBJECT_HISTORY_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return createObjectHistoryTabPanel(panelId); + } + }); + } + + tabs.add( + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.cases"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusTasksTabPanel<>(panelId, getMainForm(), getObjectModel(), + countFocusObjectTasks(parentPage) > 0); + } + + @Override + public String getCount() { + return Integer.toString(countFocusObjectTasks(parentPage)); + } + }); + + tabs.add( + new CountablePanelTab(parentPage.createStringResource("pageAdminFocus.triggers"), + getTabVisibility(ComponentConstants.UI_FOCUS_TAB_TASKS_URL, false, parentPage)){ + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new FocusTriggersTabPanel<>(panelId, getMainForm(), getObjectModel()); + } + + @Override + public String getCount() { + return Integer.toString(countFocusObjectTriggers()); + } + }); + + } + + private int countFocusObjectTasks(PageBase parentPage){ + String oid; + if (getObjectWrapper() == null || StringUtils.isEmpty(getObjectWrapper().getOid())) { + oid = "non-existent"; + } else { + oid = getObjectWrapper().getOid(); + } + ObjectQuery casesQuery = QueryUtils.filterForCasesOverUser(parentPage.getPrismContext().queryFor(CaseType.class), oid) + .desc(ItemPath.create(CaseType.F_METADATA, MetadataType.F_CREATE_TIMESTAMP)) + .build(); + return WebModelServiceUtils.countObjects(CaseType.class, casesQuery, parentPage); + } + + private int countFocusObjectTriggers(){ + PrismObjectWrapper objectWrapper = getObjectWrapper(); + if (objectWrapper.getObject() != null){ + F focusObject = objectWrapper.getObject().asObjectable(); + return focusObject.getTrigger() != null ? focusObject.getTrigger().size() : 0; + } + return 0; + } + + @Override + protected boolean areSavePreviewButtonsEnabled() { + PrismObjectWrapper focusWrapper = getObjectModel().getObject(); + PrismContainerWrapper assignmentsWrapper; + try { + assignmentsWrapper = focusWrapper.findContainer(FocusType.F_ASSIGNMENT); + } catch (SchemaException e) { + LOGGER.error("Cannot find assignment wrapper: {}", e.getMessage()); + return false; + } + return isAssignmentsModelChanged(assignmentsWrapper); + } + + protected boolean isAssignmentsModelChanged(PrismContainerWrapper assignmentsWrapper){ + if (assignmentsWrapper != null) { + for (PrismContainerValueWrapper assignmentWrapper : assignmentsWrapper.getValues()) { + if (ValueStatus.DELETED.equals(assignmentWrapper.getStatus()) || + ValueStatus.ADDED.equals(assignmentWrapper.getStatus())) { + return true; + } + } + } + return false; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java index d4a04e5f791..7b2c0217d91 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/refresh/Refreshable.java @@ -1,35 +1,35 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.web.component.refresh; - -import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; - -/** - * Refreshable page (or component). - * - * @author mederly - */ -public interface Refreshable { - - /** - * Called on manually requested refresh action. - * @param target The request target. - */ - void refresh(AjaxRequestTarget target); - - /** - * Component to which the refreshing timer should be attached. - */ - Component getRefreshingBehaviorParent(); - - /** - * Current refreshing interval (may depend on page content). - */ - int getRefreshInterval(); -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.web.component.refresh; + +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; + +/** + * Refreshable page (or component). + * + * @author mederly + */ +public interface Refreshable { + + /** + * Called on manually requested refresh action. + * @param target The request target. + */ + void refresh(AjaxRequestTarget target); + + /** + * If the refresh is enabled + */ + boolean isRefreshEnabled(); + + /** + * Current refreshing interval (may depend on page content). + */ + int getRefreshInterval(); +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java index 391a369ba62..ea972535e01 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminAbstractRole.java @@ -1,60 +1,48 @@ -/* - * Copyright (c) 2018 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.web.page.admin; - -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.prism.PrismContainerDefinition; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; - -public abstract class PageAdminAbstractRole extends PageAdminFocus { - private static final long serialVersionUID = 1L; - - public PageAdminAbstractRole() { - super(); - } - - public PageAdminAbstractRole(PageParameters parameters) { - super(parameters); - } - - public PageAdminAbstractRole(final PrismObject abstractRole) { - super(abstractRole); - } - - public PageAdminAbstractRole(final PrismObject userToEdit, boolean isNewObject) { - super(userToEdit, isNewObject); - } - - - public PageAdminAbstractRole(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { - super(abstractRole, isNewObject, isReadonly); - } - - @Override - protected void prepareObjectDeltaForModify(ObjectDelta focusDelta) throws SchemaException { - super.prepareObjectDeltaForModify(focusDelta); - - PrismObject abstractRole = getObjectWrapper().getObject(); - PrismContainerDefinition def = abstractRole.getDefinition() - .findContainerDefinition(AbstractRoleType.F_INDUCEMENT); - } - - @Override - protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { - super.prepareObjectForAdd(focus); - } - - @Override - protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { - super.initializeModel(objectToEdit, isNewObject, isReadonly); - } -} +/* + * Copyright (c) 2018 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.web.page.admin; + +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.AbstractRoleType; + +public abstract class PageAdminAbstractRole extends PageAdminFocus { + private static final long serialVersionUID = 1L; + + public PageAdminAbstractRole() { + super(); + } + + public PageAdminAbstractRole(PageParameters parameters) { + super(parameters); + } + + public PageAdminAbstractRole(final PrismObject abstractRole) { + super(abstractRole); + } + + public PageAdminAbstractRole(final PrismObject userToEdit, boolean isNewObject) { + super(userToEdit, isNewObject); + } + + + public PageAdminAbstractRole(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { + super(abstractRole, isNewObject, isReadonly); + } + + @Override + protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { + super.prepareObjectForAdd(focus); + } + + @Override + protected void initializeModel(final PrismObject objectToEdit, boolean isNewObject, boolean isReadonly) { + super.initializeModel(objectToEdit, isNewObject, isReadonly); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java index 4be3e81c3fa..7ee98ad50b6 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminFocus.java @@ -6,20 +6,10 @@ */ package com.evolveum.midpoint.web.page.admin; -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.LinkedHashMap; -import java.util.List; -import java.util.Map; -import java.util.Set; -import java.util.TreeSet; +import java.util.*; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.commons.lang.StringUtils; -import org.apache.wicket.Session; import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.protocol.http.WebSession; import org.apache.wicket.request.mapper.parameter.PageParameters; import com.evolveum.midpoint.gui.api.model.LoadableModel; @@ -32,26 +22,9 @@ import com.evolveum.midpoint.gui.impl.factory.WrapperContext; import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.model.api.context.AssignmentPath; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignment; -import com.evolveum.midpoint.model.api.context.EvaluatedAssignmentTarget; -import com.evolveum.midpoint.model.api.context.EvaluatedConstruction; -import com.evolveum.midpoint.model.api.context.ModelContext; -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.OriginType; -import com.evolveum.midpoint.prism.PrismContainerDefinition; -import com.evolveum.midpoint.prism.PrismContainerValue; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismObjectDefinition; -import com.evolveum.midpoint.prism.PrismReference; -import com.evolveum.midpoint.prism.PrismReferenceDefinition; -import com.evolveum.midpoint.prism.PrismReferenceValue; -import com.evolveum.midpoint.prism.PrismValue; -import com.evolveum.midpoint.prism.delta.ContainerDelta; -import com.evolveum.midpoint.prism.delta.DeltaSetTriple; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.delta.ReferenceDelta; +import com.evolveum.midpoint.model.api.context.*; +import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.delta.*; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.schema.SchemaRegistry; @@ -66,14 +39,12 @@ import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.component.assignment.AssignmentEditorDto; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; -import com.evolveum.midpoint.web.component.prism.show.PagePreviewChanges; import com.evolveum.midpoint.web.component.progress.ProgressReportingAwarePage; import com.evolveum.midpoint.web.page.admin.users.component.AssignmentInfoDto; import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; -import com.evolveum.midpoint.web.security.util.SecurityUtils; import com.evolveum.midpoint.web.util.validation.MidpointFormValidator; import com.evolveum.midpoint.web.util.validation.SimpleValidationError; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; public abstract class PageAdminFocus extends PageAdminObjectDetails implements ProgressReportingAwarePage { @@ -313,57 +284,6 @@ private PrismObject getPrismObjectForWrapper(Class return projection; } -// private FocusSubwrapperDto loadSubWrapperDto(Class type, String oid, boolean noFetch, Task task) { -// OperationResult subResult = task.getResult().createMinorSubresult(OPERATION_LOAD_SHADOW); -// Collection> loadOptions = new ArrayList<>(); -// PrismObject projection = getPrismObjectForWrapper(type, oid, noFetch, task, subResult, loadOptions); -// if (projection == null) { -// // No access or error -// // TODO actually it would be nice to show an error if the shadow repo object does not exist -// return null; -// } -// String resourceName = null; -// try { -// S projectionType = projection.asObjectable(); -// -// OperationResultType fetchResult = projectionType.getFetchResult(); -// StringBuilder description = new StringBuilder(); -// if (ShadowType.class.equals(type)) { -// ShadowType shadowType = (ShadowType) projectionType; -// ResourceType resource = shadowType.getResource(); -// resourceName = WebComponentUtil.getName(resource); -// -// if (shadowType.getIntent() != null) { -// description.append(shadowType.getIntent()).append(", "); -// } -// } else if (OrgType.class.equals(type)) { -// OrgType orgType = (OrgType) projectionType; -// resourceName = orgType.getDisplayName() != null -// ? WebComponentUtil.getOrigStringFromPoly(orgType.getDisplayName()) : ""; -// } -// description.append(WebComponentUtil.getOrigStringFromPoly(projectionType.getName())); -// -// ObjectWrapperOld wrapper = ObjectWrapperUtil.createObjectWrapper(resourceName, -// description.toString(), projection, ContainerStatus.MODIFYING, task, this); -// wrapper.setLoadOptions(loadOptions); -// wrapper.setFetchResult(OperationResult.createOperationResult(fetchResult)); -// wrapper.setSelectable(true); -// wrapper.setMinimalized(true); -// -//// wrapper.initializeContainers(this); -// -// subResult.computeStatus(); -// FocusSubwrapperDto ret = new FocusSubwrapperDto<>(wrapper, UserDtoStatus.MODIFY); -// return ret; -// -// } catch (Exception ex) { -// subResult.recordFatalError("Couldn't load account." + ex.getMessage(), ex); -// LoggingUtils.logUnexpectedException(LOGGER, "Couldn't load account", ex); -// subResult.computeStatus(); -// return new FocusSubwrapperDto<>(false, resourceName, subResult); -// } -// } - private List loadDelegatedToMe() { List list = new ArrayList<>(); @@ -385,17 +305,6 @@ private List loadDelegatedToMe() { return list; } - protected List getPolicyRulesList(List assignments, UserDtoStatus status){ - List list = new ArrayList<>(); - for (AssignmentType assignment : assignments) { - if (AssignmentsUtil.isPolicyRuleAssignment(assignment)) { - //TODO set status - list.add(assignment); - } - } - return list; - } - @Override protected void prepareObjectForAdd(PrismObject focus) throws SchemaException { super.prepareObjectForAdd(focus); @@ -536,16 +445,11 @@ private ObjectDelta getForceDeleteDelta(PrismObjectWrapper focusWrapper) t List refDeltas = new ArrayList<>(); ObjectDelta forceDeleteDelta = null; for (ShadowWrapper account : accounts) { -// if (!accDto.isLoadedOK()) { -// continue; -// } if (account.getProjectionStatus() == UserDtoStatus.DELETE) { -// ObjectWrapperOld accWrapper = accDto.getObjectOld(); ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, focusWrapper.getObject().getDefinition(), account.getObject()); refDeltas.add(refDelta); } else if (account.getProjectionStatus() == UserDtoStatus.UNLINK) { -// ObjectWrapperOld accWrapper = accDto.getObjectOld(); ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().createModificationDelete(UserType.F_LINK_REF, focusWrapper.getObject().getDefinition(), account.getObject().getOid()); refDeltas.add(refDelta); @@ -556,8 +460,6 @@ private ObjectDelta getForceDeleteDelta(PrismObjectWrapper focusWrapper) t .createModifyDelta(focusWrapper.getObject().getOid(), refDeltas, getCompileTimeClass()); } - PrismContainerDefinition def = focusWrapper.getObject().findContainer(UserType.F_ASSIGNMENT) - .getDefinition(); if (forceDeleteDelta == null) { forceDeleteDelta = getPrismContext().deltaFactory().object().createEmptyModifyDelta(getCompileTimeClass(), focusWrapper.getObject().getOid()); @@ -596,9 +498,6 @@ private ObjectDelta getForceDeleteDelta(PrismObjectWrapper focusWrapper) t private List prepareShadowObject(List projections) throws SchemaException{ List projectionsToAdd = new ArrayList<>(); for (ShadowWrapper projection : projections) { -// if (!projection.isLoadedOK()) { -// continue; -// } if (UserDtoStatus.MODIFY.equals(projection.getProjectionStatus())) { // this is legal e.g. when child org is being create (one assignment comes pre-created) // TODO do we need more specific checks here? @@ -630,9 +529,6 @@ private List> getShadowModifyDeltas(OperationR List accounts = getFocusShadows(); for (ShadowWrapper account : accounts) { -// if (!account.isLoadedOK()) { -// continue; -// } try { ObjectDelta delta = account.getObjectDelta(); if (LOGGER.isTraceEnabled()) { @@ -645,15 +541,9 @@ private List> getShadowModifyDeltas(OperationR } if (delta == null || delta.isEmpty()) { -// && (accountWrapper.getOldDelta() == null || accountWrapper.getOldDelta().isEmpty())) { continue; } -// if (accountWrapper.getOldDelta() != null) { -// delta = ObjectDeltaCollectionsUtil.summarize(delta, accountWrapper.getOldDelta()); -// } - - WebComponentUtil.encryptCredentials(delta, true, getMidpointApplication()); if (LOGGER.isTraceEnabled()) { LOGGER.trace("Modifying account:\n{}", new Object[] { delta.debugDump(3) }); @@ -670,31 +560,12 @@ private List> getShadowModifyDeltas(OperationR return deltas; } - /** - * remove this method after model is updated - it has to remove resource - * from accountConstruction - */ - @Deprecated - private void removeResourceFromAccConstruction(AssignmentType assignment) { - ConstructionType accConstruction = assignment.getConstruction(); - if (accConstruction == null || accConstruction.getResourceRef() == null || accConstruction.getResourceRef().asReferenceValue().getObject() == null) { - return; - } - - ObjectReferenceType ref = new ObjectReferenceType(); - ref.setOid(assignment.getConstruction().getResourceRef().getOid()); - ref.setType(ResourceType.COMPLEX_TYPE); - assignment.getConstruction().setResourceRef(ref); - } - private ReferenceDelta prepareUserAccountsDeltaForModify(PrismReferenceDefinition refDef) throws SchemaException { ReferenceDelta refDelta = getPrismContext().deltaFactory().reference().create(refDef); List accounts = getFocusShadows(); for (ShadowWrapper accountWrapper : accounts) { -// if (accDto.isLoadedOK()) { -// ObjectWrapperOld accountWrapper = accDto.getObjectOld(); accountWrapper.revive(getPrismContext()); ObjectDelta delta = accountWrapper.getObjectDelta(); PrismReferenceValue refValue = getPrismContext().itemFactory().createReferenceValue(null, OriginType.USER_ACTION, null); @@ -849,13 +720,7 @@ public List showAllAssignmentsPerformed(AjaxRequestTarget aja private AssignmentInfoDto createAssignmentsPreviewDto(EvaluatedAssignmentTarget evaluatedAbstractRole, Task task, OperationResult result) { return createAssignmentsPreviewDto(evaluatedAbstractRole.getTarget(), evaluatedAbstractRole.isDirectlyAssigned(), - evaluatedAbstractRole.getAssignmentPath(), evaluatedAbstractRole.getAssignment(), task, result); - } - - protected AssignmentInfoDto createAssignmentsPreviewDto(ObjectReferenceType reference, Task task, OperationResult result) { - PrismObject targetObject = WebModelServiceUtils.resolveReferenceNoFetch(reference, - PageAdminFocus.this, task, result); - return createAssignmentsPreviewDto(targetObject, true, null, null, task, result); + evaluatedAbstractRole.getAssignmentPath(), evaluatedAbstractRole.getAssignment()); } protected AssignmentInfoDto createDelegableAssignmentsPreviewDto(AssignmentType assignment, Task task, OperationResult result) { @@ -870,7 +735,7 @@ protected AssignmentInfoDto createDelegableAssignmentsPreviewDto(AssignmentType isDelegable = targetObject.asObjectable().isDelegable(); } if (Boolean.TRUE.equals(isDelegable)) { - return createAssignmentsPreviewDto(targetObject, true, null, assignment, task, result); + return createAssignmentsPreviewDto(targetObject, true, null, assignment); } } } @@ -878,8 +743,7 @@ protected AssignmentInfoDto createDelegableAssignmentsPreviewDto(AssignmentType } private AssignmentInfoDto createAssignmentsPreviewDto(PrismObject targetObject, - boolean isDirectlyAssigned, AssignmentPath assignmentPath, AssignmentType assignment, - Task task, OperationResult result) { + boolean isDirectlyAssigned, AssignmentPath assignmentPath, AssignmentType assignment) { AssignmentInfoDto dto = new AssignmentInfoDto(); dto.setTargetOid(targetObject.getOid()); dto.setTargetName(getNameToDisplay(targetObject)); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java index e90588c4372..d0f28488763 100755 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/PageAdminObjectDetails.java @@ -24,6 +24,7 @@ import com.evolveum.midpoint.web.component.AjaxButton; import com.evolveum.midpoint.web.component.prism.ValueStatus; import com.evolveum.midpoint.web.component.prism.show.PagePreviewChanges; +import com.evolveum.midpoint.web.component.refresh.Refreshable; import com.evolveum.midpoint.web.component.util.SelectableBean; import com.evolveum.midpoint.web.component.util.VisibleBehaviour; import com.evolveum.midpoint.web.page.admin.configuration.PageSystemConfiguration; @@ -37,6 +38,7 @@ import org.apache.wicket.Session; import org.apache.wicket.ajax.AbstractAjaxTimerBehavior; import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.behavior.Behavior; import org.apache.wicket.extensions.markup.html.tabs.ITab; @@ -85,21 +87,16 @@ * @author semancik */ public abstract class PageAdminObjectDetails extends PageAdmin - implements ProgressReportingAwarePage { + implements ProgressReportingAwarePage, Refreshable { private static final long serialVersionUID = 1L; private static final String DOT_CLASS = PageAdminObjectDetails.class.getName() + "."; - public static final String PARAM_RETURN_PAGE = "returnPage"; - private static final String OPERATION_LOAD_OBJECT = DOT_CLASS + "loadObject"; - private static final String OPERATION_LOAD_PARENT_ORGS = DOT_CLASS + "loadParentOrgs"; - private static final String OPERATION_LOAD_GUI_CONFIGURATION = DOT_CLASS + "loadGuiConfiguration"; protected static final String OPERATION_SAVE = DOT_CLASS + "save"; protected static final String OPERATION_PREVIEW_CHANGES = DOT_CLASS + "previewChanges"; protected static final String OPERATION_SEND_TO_SUBMIT = DOT_CLASS + "sendToSubmit"; protected static final String OPERATION_LOAD_ARCHETYPE_REF = DOT_CLASS + "loadArchetypeRef"; - protected static final String OPERATION_EXECUTE_CHANGES = DOT_CLASS + "executeChangesTask"; protected static final String OPERATION_EXECUTE_ARCHETYPE_CHANGES = DOT_CLASS + "executeArchetypeChanges"; protected static final String OPERATION_LOAD_FILTERED_ARCHETYPES = DOT_CLASS + "loadFilteredArchetypes"; @@ -261,7 +258,6 @@ protected void initializeModel(final PrismObject objectToEdit, boolean isNewO @Override protected PrismObjectWrapper load() { PrismObjectWrapper wrapper = loadObjectWrapper(objectToEdit, isReadonly); -// wrapper.sort(); return wrapper; } }; @@ -350,17 +346,40 @@ protected void addButtons(RepeatingView repeatingView) { initOperationalButtons(repeatingView); } }; - if (getAdditionalOperationalButtonPanelBehaviors() != null && !getAdditionalOperationalButtonPanelBehaviors().isEmpty()){ - getAdditionalOperationalButtonPanelBehaviors().forEach(this::add); - } + opButtonPanel.setOutputMarkupId(true); opButtonPanel.add(new VisibleBehaviour(() -> isEditingFocus() && opButtonPanel.buttonsExist())); + + AjaxSelfUpdatingTimerBehavior behavior = new AjaxSelfUpdatingTimerBehavior(Duration.milliseconds(getRefreshInterval())) { + private static final long serialVersionUID = 1L; + + @Override + protected void onPostProcessTarget(AjaxRequestTarget target) { + refresh(target); + } + + @Override + protected boolean shouldTrigger() { + return isRefreshEnabled(); + } + }; + + opButtonPanel.add(behavior); + add(opButtonPanel); } - protected List getAdditionalOperationalButtonPanelBehaviors(){ - return new ArrayList<>(); - } + public boolean isRefreshEnabled() { + return false; + } + + public void refresh(AjaxRequestTarget target) { + + } + + public int getRefreshInterval() { + return 30; + } protected void initOperationalButtons(RepeatingView repeatingView){ if (getObjectArchetypeRef() != null) { @@ -662,24 +681,6 @@ protected Collection> buildGetOptions() { protected abstract Class getRestartResponsePage(); - public Object findParam(String param, String oid, OperationResult result) { - - Object object = null; - - for (OperationResult subResult : result.getSubresults()) { - if (subResult != null && subResult.getParams() != null) { - if (subResult.getParams().get(param) != null - && subResult.getParams().get(OperationResult.PARAM_OID) != null - && subResult.getParams().get(OperationResult.PARAM_OID).equals(oid)) { - return subResult.getParams().get(param); - } - object = findParam(param, oid, subResult); - - } - } - return object; - } - // TODO put this into correct place protected boolean previewRequested; @@ -972,14 +973,7 @@ protected void performAdditionalValidation(PrismObject object, } public List getObjectFormTypes() { - Task task = createSimpleTask(OPERATION_LOAD_GUI_CONFIGURATION); - OperationResult result = task.getResult(); - CompiledGuiProfile adminGuiConfiguration; - try { - adminGuiConfiguration = getModelInteractionService().getCompiledGuiProfile(task, result); - } catch (ObjectNotFoundException | SchemaException | CommunicationException | ConfigurationException | SecurityViolationException | ExpressionEvaluationException e) { - throw new SystemException("Cannot load GUI configuration: "+e.getMessage(), e); - } + CompiledGuiProfile adminGuiConfiguration = getCompiledGuiProfile(); ObjectFormsType objectFormsType = adminGuiConfiguration.getObjectForms(); if (objectFormsType == null) { return null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java index 405dbc55684..bf1ba0ac656 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/archetype/PageArchetype.java @@ -1,129 +1,129 @@ -/* - * 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.web.page.admin.archetype; - -import java.util.List; - -import org.apache.wicket.Page; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.model.PropertyModel; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import com.evolveum.midpoint.gui.api.ComponentConstants; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; -import com.evolveum.midpoint.gui.impl.factory.ItemRealValueModel; -import com.evolveum.midpoint.gui.impl.page.admin.configuration.component.ContainerOfSystemConfigurationPanel; -import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.security.api.AuthorizationConstants; -import com.evolveum.midpoint.web.application.AuthorizationAction; -import com.evolveum.midpoint.web.application.PageDescriptor; -import com.evolveum.midpoint.web.component.ObjectSummaryPanel; -import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; -import com.evolveum.midpoint.web.component.objectdetails.AbstractRoleMainPanel; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; -import com.evolveum.midpoint.web.page.admin.PageAdminAbstractRole; -import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypePolicyType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypeType; - -@PageDescriptor( - url = "/admin/archetype", - encoder = OnePageParameterEncoder.class, - action = { - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPES_ALL_URL, - label = "PageArchetypes.auth.archetypesAll.label", - description = "PageArchetypes.auth.archetypesAll.description"), - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPE_URL, - label = "PageArchetype.auth.user.label", - description = "PageArchetype.auth.archetype.description") - }) -public class PageArchetype extends PageAdminAbstractRole { - - private static final long serialVersionUID = 1L; - - public PageArchetype() { - super(); - } - - public PageArchetype(PageParameters parameters) { - super(parameters); - } - - public PageArchetype(final PrismObject role) { - super(role); - } - - public PageArchetype(final PrismObject userToEdit, boolean isNewObject) { - super(userToEdit, isNewObject); - } - - public PageArchetype(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { - super(abstractRole, isNewObject, isReadonly); - } - - - @Override - public Class getCompileTimeClass() { - return ArchetypeType.class; - } - - @Override - protected ArchetypeType createNewObject() { - return new ArchetypeType(getPrismContext()); - } - - @Override - protected ObjectSummaryPanel createSummaryPanel() { - IModel> valueModel = new PropertyModel>(getObjectModel(), "value"); - return new ArchetypeSummaryPanel(ID_SUMMARY_PANEL, new ItemRealValueModel(valueModel), this); - - } - - @Override - protected AbstractObjectMainPanel createMainPanel(String id) { - return new AbstractRoleMainPanel(id, getObjectModel(), getProjectionModel(), this) { - - private static final long serialVersionUID = 1L; - - @Override - public AbstractRoleMemberPanel createMemberPanel(String panelId) { - return new ArchetypeMembersPanel(panelId, new Model<>(getObject().asObjectable())); - } - - @Override - protected List createTabs(PageAdminObjectDetails parentPage) { - List tabs = super.createTabs(parentPage); - tabs.add( - new PanelTab(parentPage.createStringResource("PageArchetype.archetypePolicy"), - getTabVisibility(ComponentConstants.UI_ARCHTYPE_TAB_ARCHETYPE_POLICY_URL, false, parentPage)) { - - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new ContainerOfSystemConfigurationPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ArchetypeType.F_ARCHETYPE_POLICY), ArchetypePolicyType.COMPLEX_TYPE); - } - }); - - return tabs; - } - }; - - } - - @Override - protected Class getRestartResponsePage() { - return PageArchetypes.class; - } - -} +/* + * 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.web.page.admin.archetype; + +import java.util.List; + +import org.apache.wicket.Page; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.model.PropertyModel; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import com.evolveum.midpoint.gui.api.ComponentConstants; +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.impl.factory.ItemRealValueModel; +import com.evolveum.midpoint.gui.impl.page.admin.configuration.component.ContainerOfSystemConfigurationPanel; +import com.evolveum.midpoint.gui.impl.prism.PrismObjectValueWrapper; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.security.api.AuthorizationConstants; +import com.evolveum.midpoint.web.application.AuthorizationAction; +import com.evolveum.midpoint.web.application.PageDescriptor; +import com.evolveum.midpoint.web.component.ObjectSummaryPanel; +import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; +import com.evolveum.midpoint.web.component.objectdetails.AbstractRoleMainPanel; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.web.page.admin.PageAdminAbstractRole; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.web.page.admin.roles.AbstractRoleMemberPanel; +import com.evolveum.midpoint.web.util.OnePageParameterEncoder; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypePolicyType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ArchetypeType; + +@PageDescriptor( + url = "/admin/archetype", + encoder = OnePageParameterEncoder.class, + action = { + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPES_ALL_URL, + label = "PageArchetypes.auth.archetypesAll.label", + description = "PageArchetypes.auth.archetypesAll.description"), + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_ARCHETYPE_URL, + label = "PageArchetype.auth.user.label", + description = "PageArchetype.auth.archetype.description") + }) +public class PageArchetype extends PageAdminAbstractRole { + + private static final long serialVersionUID = 1L; + + public PageArchetype() { + super(); + } + + public PageArchetype(PageParameters parameters) { + super(parameters); + } + + public PageArchetype(final PrismObject role) { + super(role); + } + + public PageArchetype(final PrismObject userToEdit, boolean isNewObject) { + super(userToEdit, isNewObject); + } + + public PageArchetype(final PrismObject abstractRole, boolean isNewObject, boolean isReadonly) { + super(abstractRole, isNewObject, isReadonly); + } + + + @Override + public Class getCompileTimeClass() { + return ArchetypeType.class; + } + + @Override + protected ArchetypeType createNewObject() { + return new ArchetypeType(getPrismContext()); + } + + @Override + protected ObjectSummaryPanel createSummaryPanel() { + IModel> valueModel = new PropertyModel<>(getObjectModel(), "value"); + return new ArchetypeSummaryPanel(ID_SUMMARY_PANEL, new ItemRealValueModel<>(valueModel), this); + + } + + @Override + protected AbstractObjectMainPanel createMainPanel(String id) { + return new AbstractRoleMainPanel(id, getObjectModel(), getProjectionModel(), this) { + + private static final long serialVersionUID = 1L; + + @Override + public AbstractRoleMemberPanel createMemberPanel(String panelId) { + return new ArchetypeMembersPanel(panelId, new Model<>(getObject().asObjectable())); + } + + @Override + protected List createTabs(PageAdminObjectDetails parentPage) { + List tabs = super.createTabs(parentPage); + tabs.add( + new PanelTab(parentPage.createStringResource("PageArchetype.archetypePolicy"), + getTabVisibility(ComponentConstants.UI_ARCHTYPE_TAB_ARCHETYPE_POLICY_URL, false, parentPage)) { + + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new ContainerOfSystemConfigurationPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ArchetypeType.F_ARCHETYPE_POLICY), ArchetypePolicyType.COMPLEX_TYPE); + } + }); + + return tabs; + } + }; + + } + + @Override + protected Class getRestartResponsePage() { + return PageArchetypes.class; + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java index 67e6061a71b..1d74f22a604 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java @@ -1,66 +1,50 @@ package com.evolveum.midpoint.web.page.admin.server; +import java.util.Collection; +import java.util.Collections; + +import org.apache.wicket.Component; +import org.apache.wicket.Page; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.repeater.RepeatingView; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; + import com.evolveum.midpoint.gui.api.GuiStyleConstants; -import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; import com.evolveum.midpoint.gui.api.model.LoadableModel; -import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; -import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.impl.prism.ItemEditabilityHandler; -import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; -import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; -import com.evolveum.midpoint.prism.Containerable; +import com.evolveum.midpoint.gui.impl.prism.PrismPropertyWrapper; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.task.api.TaskCategory; +import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.application.AuthorizationAction; import com.evolveum.midpoint.web.application.PageDescriptor; import com.evolveum.midpoint.web.application.Url; -import com.evolveum.midpoint.web.component.*; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.AjaxIconButton; +import com.evolveum.midpoint.web.component.ObjectSummaryPanel; import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; -import com.evolveum.midpoint.web.component.prism.ItemVisibility; import com.evolveum.midpoint.web.component.refresh.Refreshable; import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; -import com.evolveum.midpoint.web.page.admin.server.dto.TaskDtoExecutionStatus; import com.evolveum.midpoint.web.util.OnePageParameterEncoder; import com.evolveum.midpoint.web.util.TaskOperationUtils; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationStatsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskExecutionStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskRecurrenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; - -import org.apache.wicket.Component; -import org.apache.wicket.Page; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.AjaxSelfUpdatingTimerBehavior; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.behavior.Behavior; -import org.apache.wicket.extensions.markup.html.tabs.AbstractTab; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.markup.repeater.RepeatingView; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; -import org.apache.wicket.util.time.Duration; - -import javax.xml.namespace.QName; -import java.util.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @PageDescriptor( urls = { @@ -82,11 +66,7 @@ public class PageTask extends PageAdminObjectDetails implements Refres private static final String DOT_CLASS = PageTask.class.getName() + "."; protected static final String OPERATION_EXECUTE_TASK_CHANGES = DOT_CLASS + "executeTaskChanges"; - private static final int REFRESH_INTERVAL_IF_RUNNING = 2000; - private static final int REFRESH_INTERVAL_IF_RUNNABLE = 2000; - private static final int REFRESH_INTERVAL_IF_SUSPENDED = 2000; - private static final int REFRESH_INTERVAL_IF_WAITING = 2000; - private static final int REFRESH_INTERVAL_IF_CLOSED = 2000; + private static final int REFRESH_INTERVAL = 2000; private Boolean refreshEnabled; @@ -136,20 +116,12 @@ protected Collection> buildGetOptions() { .build(); } - @Override - protected void initLayout() { - super.initLayout(); - - } - private void afterOperation(AjaxRequestTarget target, OperationResult result) { showResult(result); getObjectModel().reset(); refresh(target); } - - protected void initOperationalButtons(RepeatingView repeatingView) { super.initOperationalButtons(repeatingView); AjaxButton suspend = new AjaxButton(repeatingView.newChildId(), createStringResource("pageTaskEdit.button.suspend")) { @@ -204,7 +176,6 @@ public void onClick(AjaxRequestTarget target) { @Override public void onClick(AjaxRequestTarget target) { refreshEnabled = !isRefreshEnabled(); -// getModelObject().setEnabled(!getModelObject().isEnabled()); refresh(target); } }; @@ -263,7 +234,7 @@ public void onClick(AjaxRequestTarget target) { setOutputMarkupId(true); - final Label status = new Label(repeatingView.newChildId(), () -> createRefreshingLabel()); + final Label status = new Label(repeatingView.newChildId(), this::createRefreshingLabel); status.setOutputMarkupId(true); repeatingView.add(status); @@ -276,7 +247,7 @@ private void saveTaskChanges(){ ObjectDelta taskDelta = getObjectWrapper().getObjectDelta(); if (!taskDelta.isEmpty()) { taskDelta.revive(getPrismContext()); - getModelService().executeChanges(WebComponentUtil.createDeltaCollection(taskDelta), null, task, result); + getModelService().executeChanges(MiscUtil.createCollection(taskDelta), null, task, result); result.computeStatus(); getObjectModel().reset(); } @@ -286,6 +257,47 @@ private void saveTaskChanges(){ showResult(result); } + public void saveAndRunPerformed(AjaxRequestTarget target) { + PrismObjectWrapper taskWrapper = getObjectWrapper(); + try { + PrismPropertyWrapper executionStatus = taskWrapper.findProperty(ItemPath.create(TaskType.F_EXECUTION_STATUS)); + executionStatus.getValue().setRealValue(TaskExecutionStatusType.RUNNABLE); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Error while setting task execution status", e); + target.add(getFeedbackPanel()); + return; + } + + if (!checkScheduleFilledForReccurentTask(taskWrapper)) { + getSession().error("Cannot run recurring task without setting scheduling for it."); + target.add(getFeedbackPanel()); + return; + } + + super.savePerformed(target); + } + + private boolean checkScheduleFilledForReccurentTask(PrismObjectWrapper taskWrapper) { + PrismObject task = taskWrapper.getObject(); + + PrismProperty recurrenceType = task.findProperty(ItemPath.create(TaskType.F_RECURRENCE)); + if (recurrenceType == null) { + return true; + } + + TaskRecurrenceType recurenceValue = recurrenceType.getRealValue(); + if (recurenceValue == null || TaskRecurrenceType.SINGLE == recurenceValue) { + return true; + } + + ScheduleType schedule = task.asObjectable().getSchedule(); + //if schedule is not set and task is recurring, show warning. + return schedule.getCronLikePattern() != null || schedule.getEarliestStartTime() != null + || schedule.getInterval() != null || schedule.getLatestFinishTime() != null + || schedule.getLatestStartTime() != null || schedule.getMisfireAction() != null; + } + + private String createRefreshingLabel() { if (isRefreshEnabled()) { return createStringResource("autoRefreshPanel.refreshingEach", getRefreshInterval() / 1000).getString(); @@ -318,263 +330,10 @@ protected TaskType load() { @Override protected AbstractObjectMainPanel createMainPanel(String id) { - - return new AbstractObjectMainPanel(id, getObjectModel(), this) { - - @Override - protected boolean getOptionsPanelVisibility() { - return false; - } - - @Override - protected List createTabs(PageAdminObjectDetails parentPage) { - List tabs = new ArrayList<>(); - TaskTabsVisibility taskTabsVisibility = new TaskTabsVisibility(); - taskTabsVisibility.computeAll(PageTask.this, getObjectWrapper()); - - ObjectTabVisibleBehavior basicTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isBasicVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.basic.title"), basicTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> getBasicTabVisibility(wrapper.getPath()); - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, getObjectModel(), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior scheduleTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isSchedulingVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.schedule.title"), scheduleTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_SCHEDULE), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior workManagementTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isWorkManagementVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.workManagement.title"), workManagementTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_WORK_MANAGEMENT), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior cleanupPoliciesTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isCleanupPolicyVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.cleanupPolicies.title"), cleanupPoliciesTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; - return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES)), visibilityHandler); - } - }); - - ObjectTabVisibleBehavior subtasksTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isSubtasksAndThreadsVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.subtasks.title"), subtasksTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskSubtasksAndThreadsTabPanel(panelId, getObjectModel()); - } - - }); - - ObjectTabVisibleBehavior operationStatsAndInternalPerfTabsVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isInternalPerformanceVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.operationStats.title"), operationStatsAndInternalPerfTabsVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskOperationStatisticsPanel(panelId, getObjectModel()); - } - - }); - - ObjectTabVisibleBehavior envPerfTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isEnvironmentalPerformanceVisible(); - } - }; - tabs.add(new PanelTab(parentPage.createStringResource("pageTask.environmentalPerformance.title"), envPerfTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskPerformanceTabPanel(panelId, getObjectModel()); - } - - }); - - ObjectTabVisibleBehavior operationTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isOperationVisible(); - } - }; - tabs.add(new PanelTab(parentPage.createStringResource("pageTaskEdit.operation"), operationTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskOperationTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_MODEL_OPERATION_CONTEXT)); - } - }); - - tabs.add(new PanelTab(createStringResource("pageTask.internalPerformance.title"), operationStatsAndInternalPerfTabsVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskInternalPerformanceTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_OPERATION_STATS)); - } - }); - - ObjectTabVisibleBehavior resultTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isResultVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.result.title"), resultTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskResultTabPanel(panelId, getObjectModel()); - } - }); - - - ObjectTabVisibleBehavior errorsTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", PageTask.this){ - - private static final long serialVersionUID = 1L; - - @Override - public boolean isVisible(){ - return taskTabsVisibility.isErrorsVisible(); - } - }; - tabs.add(new PanelTab(createStringResource("pageTask.errors.title"), errorsTabVisibility) { - private static final long serialVersionUID = 1L; - - @Override - public WebMarkupContainer createPanel(String panelId) { - return new TaskErrorsTabPanel(panelId, getObjectModel()); - } - }); - - return tabs; - } - }; - } - - - - private Panel createContainerPanel(String id, QName typeName, IModel> model, ItemVisibilityHandler visibilityHandler) { - try { - ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder() - .visibilityHandler(visibilityHandler) - .editabilityHandler(getTaskEditabilityHandler()) - .showOnTopLevel(true); - Panel panel = initItemPanel(id, typeName, model, builder.build()); - return panel; - } catch (SchemaException e) { - LOGGER.error("Cannot create panel for {}, {}", typeName, e.getMessage(), e); - getSession().error("Cannot create panel for " + typeName); // TODO opertion result? localization? - } - - return null; + return new TaskMainPanel(id, getObjectModel(), this); } - private ItemVisibility getBasicTabVisibility(ItemPath path) { - if (ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES).equivalent(path)) { - return ItemVisibility.HIDDEN; - } - return ItemVisibility.AUTO; - } - - private ItemEditabilityHandler getTaskEditabilityHandler(){ - ItemEditabilityHandler editableHandler = wrapper -> !WebComponentUtil.isRunningTask(getTask()); - return editableHandler; - } - - private TaskType getTask(){ + TaskType getTask(){ return getObjectWrapper().getObject().asObjectable(); } @@ -582,61 +341,23 @@ private TaskType getTask(){ protected Class getRestartResponsePage() { return PageTasks.class; } - - @Override - public void continueEditing(AjaxRequestTarget target) { - - } @Override - protected List getAdditionalOperationalButtonPanelBehaviors(){ - AjaxSelfUpdatingTimerBehavior behavior = new AjaxSelfUpdatingTimerBehavior(Duration.milliseconds(getRefreshInterval())) { - private static final long serialVersionUID = 1L; - - @Override - protected void onPostProcessTarget(AjaxRequestTarget target) { - refresh(target); - } + public void continueEditing(AjaxRequestTarget target) { - @Override - protected boolean shouldTrigger() { - PageTask.this.getObjectModel().reset(); - return isRefreshEnabled(); - } - }; - return Collections.singletonList(behavior); } @Override public int getRefreshInterval() { - TaskType task = getTask(); - TaskDtoExecutionStatus exec = TaskDtoExecutionStatus.fromTaskExecutionStatus(task.getExecutionStatus(), task.getNodeAsObserved() != null); - if (exec == null) { - return REFRESH_INTERVAL_IF_CLOSED; - } - switch (exec) { - case RUNNING: - case SUSPENDING: return REFRESH_INTERVAL_IF_RUNNING; - case RUNNABLE:return REFRESH_INTERVAL_IF_RUNNABLE; - case SUSPENDED: return REFRESH_INTERVAL_IF_SUSPENDED; - case WAITING: return REFRESH_INTERVAL_IF_WAITING; - case CLOSED: return REFRESH_INTERVAL_IF_CLOSED; - } - return REFRESH_INTERVAL_IF_RUNNABLE; - } - - @Override - public Component getRefreshingBehaviorParent() { - return null; //nothing to do, this method will be removed + return REFRESH_INTERVAL; } public void refresh(AjaxRequestTarget target) { -// getObjectModel().reset(); target.add(getSummaryPanel()); target.add(getOperationalButtonsPanel()); target.add(getFeedbackPanel()); - target.add(getMainPanel()); +// target.add(getMainPanel()); for (Component component : getMainPanel().getTabbedPanel()) { if (component instanceof TaskTabPanel) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.html new file mode 100644 index 00000000000..2e8bf153a32 --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.html @@ -0,0 +1,17 @@ + + + + + + + + + + + + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java new file mode 100644 index 00000000000..9f9d328c427 --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java @@ -0,0 +1,345 @@ +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin.server; + +import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.ItemStatus; +import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.api.util.ObjectTabVisibleBehavior; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.gui.impl.prism.ItemEditabilityHandler; +import com.evolveum.midpoint.gui.impl.prism.ItemPanelSettingsBuilder; +import com.evolveum.midpoint.gui.impl.prism.ItemVisibilityHandler; +import com.evolveum.midpoint.prism.Containerable; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.AjaxSubmitButton; +import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; +import com.evolveum.midpoint.web.component.prism.ItemVisibility; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; +import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; +import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; + +import javax.xml.namespace.QName; +import java.util.ArrayList; +import java.util.List; + +public class TaskMainPanel extends AbstractObjectMainPanel { + + private static final transient Trace LOGGER = TraceManager.getTrace(TaskMainPanel.class); + + private static final String ID_SAVE_AND_RUN = "saveAndRun"; + private static final String ID_FORM = "taskForm"; + + public TaskMainPanel(String id, LoadableModel> objectModel, PageAdminObjectDetails parentPage) { + super(id, objectModel, parentPage); + } + + @Override + protected boolean getOptionsPanelVisibility() { + return false; + } + + @Override + protected void initLayoutButtons(PageAdminObjectDetails parentPage) { + super.initLayoutButtons(parentPage); + initLayoutSaveAndRunButton(); + } + + @Override + protected List createTabs(PageAdminObjectDetails parentPage) { + List tabs = new ArrayList<>(); + TaskTabsVisibility taskTabsVisibility = new TaskTabsVisibility(); + taskTabsVisibility.computeAll((PageTask) parentPage, getObjectWrapper()); + + ObjectTabVisibleBehavior basicTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", (PageTask) parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isBasicVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.basic.title"), basicTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> getBasicTabVisibility(wrapper.getPath()); + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, getObjectModel(), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior scheduleTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isSchedulingVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.schedule.title"), scheduleTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_SCHEDULE), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior workManagementTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isWorkManagementVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.workManagement.title"), workManagementTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_WORK_MANAGEMENT), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior cleanupPoliciesTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isCleanupPolicyVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.cleanupPolicies.title"), cleanupPoliciesTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + ItemVisibilityHandler visibilityHandler = wrapper -> ItemVisibility.AUTO; + return createContainerPanel(panelId, TaskType.COMPLEX_TYPE, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES)), visibilityHandler); + } + }); + + ObjectTabVisibleBehavior subtasksTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isSubtasksAndThreadsVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.subtasks.title"), subtasksTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskSubtasksAndThreadsTabPanel(panelId, getObjectModel()); + } + + }); + + ObjectTabVisibleBehavior operationStatsAndInternalPerfTabsVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isInternalPerformanceVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.operationStats.title"), operationStatsAndInternalPerfTabsVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskOperationStatisticsPanel(panelId, getObjectModel()); + } + + }); + + ObjectTabVisibleBehavior envPerfTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isEnvironmentalPerformanceVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.environmentalPerformance.title"), envPerfTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskPerformanceTabPanel(panelId, getObjectModel()); + } + + }); + + ObjectTabVisibleBehavior operationTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isOperationVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTaskEdit.operation"), operationTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskOperationTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_MODEL_OPERATION_CONTEXT)); + } + }); + + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.internalPerformance.title"), operationStatsAndInternalPerfTabsVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskInternalPerformanceTabPanel(panelId, PrismContainerWrapperModel.fromContainerWrapper(getObjectModel(), TaskType.F_OPERATION_STATS)); + } + }); + + ObjectTabVisibleBehavior resultTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isResultVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.result.title"), resultTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskResultTabPanel(panelId, getObjectModel()); + } + }); + + + ObjectTabVisibleBehavior errorsTabVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), "", parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return taskTabsVisibility.isErrorsVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.errors.title"), errorsTabVisibility) { + private static final long serialVersionUID = 1L; + + @Override + public WebMarkupContainer createPanel(String panelId) { + return new TaskErrorsTabPanel(panelId, getObjectModel()); + } + }); + + return tabs; + } + + protected void initLayoutSaveAndRunButton() { + AjaxSubmitButton saveButton = new AjaxSubmitButton(ID_SAVE_AND_RUN, getDetailsPage().createStringResource("pageAdminFocus.button.saveAndRun")) { + private static final long serialVersionUID = 1L; + + @Override + protected void onSubmit(AjaxRequestTarget target) { + ((PageTask)getDetailsPage()).saveAndRunPerformed(target); + } + + @Override + protected void onError(AjaxRequestTarget target) { + target.add(getDetailsPage().getFeedbackPanel()); + } + }; + saveButton.add(new VisibleEnableBehaviour(){ + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible() { + return !getObjectWrapper().isReadOnly() && + !getDetailsPage().isForcedPreview(); + } + + @Override + public boolean isEnabled() { + return !ItemStatus.NOT_CHANGED.equals(getObjectWrapper().getStatus()) + || getObjectWrapper().canModify(); + } + }); + saveButton.setOutputMarkupId(true); + saveButton.setOutputMarkupPlaceholderTag(true); + getMainForm().add(saveButton); + } + + + private Panel createContainerPanel(String id, QName typeName, IModel> model, ItemVisibilityHandler visibilityHandler) { + try { + ItemPanelSettingsBuilder builder = new ItemPanelSettingsBuilder() + .visibilityHandler(visibilityHandler) + .editabilityHandler(getTaskEditabilityHandler()) + .showOnTopLevel(true); + Panel panel = getDetailsPage().initItemPanel(id, typeName, model, builder.build()); + return panel; + } catch (SchemaException e) { + LOGGER.error("Cannot create panel for {}, {}", typeName, e.getMessage(), e); + getSession().error("Cannot create panel for " + typeName); // TODO opertion result? localization? + } + + return null; + } + + private ItemVisibility getBasicTabVisibility(ItemPath path) { + if (ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.MODEL_EXTENSION_CLEANUP_POLICIES).equivalent(path)) { + return ItemVisibility.HIDDEN; + } + return ItemVisibility.AUTO; + } + + + private ItemEditabilityHandler getTaskEditabilityHandler(){ + ItemEditabilityHandler editableHandler = wrapper -> !WebComponentUtil.isRunningTask(((PageTask)getDetailsPage()).getTask()); + return editableHandler; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java index a369f22bbd1..d84ffd0b0ea 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java @@ -88,17 +88,17 @@ public boolean configuresWorkerThreads(TaskType task) { public boolean computeEnvironmentalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { final OperationStatsType operationStats = taskWrapper.getObject().asObjectable().getOperationStats(); - environmentalPerformanceVisible = !parentPage.isAdd() && !parentPage.isEditingFocus() - && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) - && operationStats != null - && !StatisticsUtil.isEmpty(operationStats.getEnvironmentalPerformanceInformation()); + environmentalPerformanceVisible = parentPage.isEditingFocus(); +// && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) +// && operationStats != null +// && !StatisticsUtil.isEmpty(operationStats.getEnvironmentalPerformanceInformation()); return environmentalPerformanceVisible; } public boolean computeInternalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { - internalPerformanceVisible = !parentPage.isAdd() &&!parentPage.isEditingFocus() - && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) - && taskWrapper.getObject().asObjectable().getOperationStats() != null; + internalPerformanceVisible = parentPage.isEditingFocus(); +// && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) +// && taskWrapper.getObject().asObjectable().getOperationStats() != null; return internalPerformanceVisible; } @@ -109,7 +109,7 @@ public boolean computeOperationVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { - resultVisible = !parentPage.isAdd() && !parentPage.isEditingFocus() + resultVisible = parentPage.isEditingFocus() && isTaskItemReadable(taskWrapper, TaskType.F_RESULT) && !WebComponentUtil.isWorkflowTask(taskWrapper.getObject().asObjectable()); return resultVisible; } public boolean computeErrorsVisible(PageTask parentPage, TaskType task) { - errorsVisible = !parentPage.isAdd() && !parentPage.isEditingFocus() + errorsVisible = parentPage.isEditingFocus() && !WebComponentUtil.isWorkflowTask(task); return errorsVisible; } @@ -144,7 +144,7 @@ public void computeAll(PageTask parentPage, PrismObjectWrapper taskWra } public boolean computeProgressVisible(PageTask parentPage) { - progressVisible = !parentPage.isEditingFocus(); + progressVisible = parentPage.isEditingFocus(); return progressVisible; } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java index fde0dd09d59..7b28f50546f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/users/PageUser.java @@ -6,21 +6,34 @@ */ package com.evolveum.midpoint.web.page.admin.users; +import static org.apache.commons.collections4.CollectionUtils.addIgnoreNull; + +import java.util.*; + +import org.apache.commons.lang3.StringUtils; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.tabs.ITab; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; +import org.apache.wicket.request.mapper.parameter.PageParameters; + import com.evolveum.midpoint.gui.api.ComponentConstants; import com.evolveum.midpoint.gui.api.component.tabs.CountablePanelTab; import com.evolveum.midpoint.gui.api.model.LoadableModel; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; import com.evolveum.midpoint.model.api.context.ModelContext; -import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.PrismContainerDefinition; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.query.ObjectFilter; import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.security.api.AuthorizationConstants; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.util.logging.LoggingUtils; import com.evolveum.midpoint.util.logging.Trace; @@ -43,23 +56,7 @@ import com.evolveum.midpoint.web.page.admin.users.component.UserSummaryPanel; import com.evolveum.midpoint.web.page.admin.users.dto.UserDtoStatus; import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RelationKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.apache.commons.lang3.StringUtils; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.tabs.ITab; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import java.util.*; - -import static org.apache.commons.collections4.CollectionUtils.addIgnoreNull; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author lazyman @@ -140,7 +137,7 @@ protected FocusSummaryPanel createSummaryPanel() { Model.of(getObjectModel().getObject().getObject().asObjectable()) : Model.of(), this); } - protected void cancelPerformed(AjaxRequestTarget target) { + protected void cancelPerformed() { redirectBack(); } @@ -266,8 +263,10 @@ protected boolean getOptionsPanelVisibility() { @Override protected boolean areSavePreviewButtonsEnabled(){ - return super.areSavePreviewButtonsEnabled() || - (userDelegationsTabPanel != null ? userDelegationsTabPanel.isDelegationsModelChanged() : false); + if (super.areSavePreviewButtonsEnabled()) { + return true; + } + return userDelegationsTabPanel != null && userDelegationsTabPanel.isDelegationsModelChanged(); } @Override @@ -356,7 +355,7 @@ protected boolean processDeputyAssignments(boolean previewOnly) { /** * for now used only for delegation changes - * @param modelContextMap + * @param modelContextMap preview changes deltas */ @Override protected void processAdditionalFocalObjectsForPreview(Map, ModelContext> modelContextMap){ @@ -420,31 +419,4 @@ public boolean isLoggedInUserPage(){ getObjectWrapper().getObject().asObjectable().getOid().equals(WebModelServiceUtils.getLoggedInFocusOid()); } - protected int countConsents() { - int consentCounter = 0; - PrismObject focus = getObjectModel().getObject().getObject(); - List assignments = focus.asObjectable().getAssignment(); - for (AssignmentType assignment : assignments) { - if (isConsentAssignment(assignment)) { - consentCounter++; - } - } - return consentCounter; - } - - private boolean isConsentAssignment(AssignmentType assignment) { - return assignment.getTargetRef() != null && QNameUtil.match(assignment.getTargetRef().getRelation(), SchemaConstants.ORG_CONSENT); - } - - protected List getConsentsList(List assignments, UserDtoStatus status){ - List list = new ArrayList<>(); - for (AssignmentType assignment : assignments) { - if (isConsentAssignment(assignment)) { - //TODO set status - list.add(assignment); - } - } - return list; - } - } diff --git a/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml b/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml index 79b9339bf5e..06b08f58cc8 100644 --- a/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml +++ b/gui/admin-gui/src/main/resources/initial-objects/000-system-configuration.xml @@ -475,6 +475,7 @@ 910 + hidden @@ -488,7 +489,7 @@ stalledSince - + From c23b5a044f18b996d2343fb7d963bea9e28a9b74 Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Sun, 8 Mar 2020 08:13:19 +0100 Subject: [PATCH 25/55] finishing MID-5959 (recompute members task configuration) --- .../gui/api/util/WebComponentUtil.java | 50 + .../admin/roles/AbstractRoleMemberPanel.java | 2504 +++++++++-------- .../admin/roles/MemberOperationsHelper.java | 13 +- .../model/api/ModelPublicConstants.java | 91 +- 4 files changed, 1364 insertions(+), 1294 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java index 995f3ae9d3e..f5384a7f08d 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java @@ -746,6 +746,56 @@ public static Task createMemberOperationTask(Task operationalTask, QName type, O return null; } + public static Task createRecomputeMemberOperationTask(Task operationalTask, QName type, ObjectQuery memberQuery, + Collection> option, OperationResult parentResult, PageBase pageBase) throws SchemaException { + + MidPointPrincipal owner = SecurityUtils.getPrincipalUser(); + operationalTask.setOwner(owner.getFocus().asPrismObject()); + + operationalTask.setBinding(TaskBinding.LOOSE); + operationalTask.setInitialExecutionStatus(TaskExecutionStatus.RUNNABLE); + operationalTask.setThreadStopAction(ThreadStopActionType.RESTART); + ScheduleType schedule = new ScheduleType(); + schedule.setMisfireAction(MisfireActionType.EXECUTE_IMMEDIATELY); + operationalTask.makeSingle(schedule); + operationalTask.setName(WebComponentUtil.createPolyFromOrigString(parentResult.getOperation())); + + PrismPropertyDefinition propertyDefQuery = pageBase.getPrismContext().getSchemaRegistry() + .findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_OBJECT_QUERY); + PrismProperty queryProperty = propertyDefQuery.instantiate(); + QueryType queryType = pageBase.getQueryConverter().createQueryType(memberQuery); + queryProperty.setRealValue(queryType); + operationalTask.addExtensionProperty(queryProperty); + + PrismPropertyDefinition propertyDefType = pageBase.getPrismContext().getSchemaRegistry() + .findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_OBJECT_TYPE); + PrismProperty typeProperty = propertyDefType.instantiate(); + typeProperty.setRealValue(type); + operationalTask.addExtensionProperty(typeProperty); + + if (option != null) { + PrismPropertyDefinition propertyDefOption = pageBase.getPrismContext().getSchemaRegistry() + .findPropertyDefinitionByElementName(SchemaConstants.MODEL_EXTENSION_SEARCH_OPTIONS); + PrismProperty optionProperty = propertyDefOption.instantiate(); + optionProperty.setRealValue(MiscSchemaUtil.optionsToOptionsType(option)); + operationalTask.addExtensionProperty(optionProperty); + } + + try { + pageBase.getSecurityEnforcer().authorize(ModelAuthorizationAction.RECOMPUTE.getUrl(), + null, AuthorizationParameters.EMPTY, null, operationalTask, parentResult); + operationalTask.setHandlerUri(ModelPublicConstants.RECOMPUTE_HANDLER_URI); + return operationalTask; + } catch (ObjectNotFoundException | SchemaException + | ExpressionEvaluationException | CommunicationException | ConfigurationException + | SecurityViolationException e) { + parentResult.recordFatalError(pageBase.createStringResource("WebComponentUtil.message.startPerformed.fatalError.createTask").getString(), e); + LoggingUtils.logUnexpectedException(LOGGER, "Couldn't create bulk action task", e); + } + return null; + } + + public static void executeMemberOperation(Task operationalTask, OperationResult parentResult, PageBase pageBase) { OperationResult result = parentResult.createSubresult("evaluateExpressionInBackground"); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java index f90c8bcba3c..2ddcced44f8 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java @@ -1,1248 +1,1256 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ -package com.evolveum.midpoint.web.page.admin.roles; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -import javax.xml.namespace.QName; - -import com.evolveum.midpoint.gui.impl.component.icon.CompositedIcon; -import com.evolveum.midpoint.gui.impl.component.icon.CompositedIconBuilder; -import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; -import com.evolveum.midpoint.model.api.AssignmentObjectRelation; -import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.polystring.PolyString; -import com.evolveum.midpoint.prism.query.QueryFactory; -import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty; -import com.evolveum.midpoint.schema.constants.RelationTypes; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.web.component.MultiFunctinalButtonDto; -import com.evolveum.midpoint.web.component.MultifunctionalButton; -import com.evolveum.midpoint.web.component.data.column.ColumnUtils; -import com.evolveum.midpoint.web.component.dialog.ConfigureTaskConfirmationPanel; -import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; -import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; -import com.evolveum.midpoint.web.component.util.SelectableBean; -import com.evolveum.midpoint.web.page.admin.configuration.component.HeaderMenuAction; -import com.evolveum.midpoint.web.session.MemberPanelStorage; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.apache.commons.collections.CollectionUtils; -import org.apache.commons.lang.StringUtils; -import org.apache.wicket.Component; -import org.apache.wicket.RestartResponseException; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; -import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; -import org.apache.wicket.behavior.AttributeAppender; -import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; -import org.apache.wicket.markup.html.WebMarkupContainer; -import org.apache.wicket.markup.html.basic.Label; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.markup.html.form.IChoiceRenderer; -import org.apache.wicket.markup.repeater.Item; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; - -import com.evolveum.midpoint.gui.api.GuiStyleConstants; -import com.evolveum.midpoint.gui.api.component.BasePanel; -import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; -import com.evolveum.midpoint.gui.api.page.PageBase; -import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.prism.PrismConstants; -import com.evolveum.midpoint.prism.query.ObjectFilter; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.GetOperationOptions; -import com.evolveum.midpoint.schema.SelectorOptions; -import com.evolveum.midpoint.schema.constants.ObjectTypes; -import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.util.QNameUtil; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.dialog.ChooseFocusTypeAndRelationDialogPanel; -import com.evolveum.midpoint.web.component.form.CheckFormGroup; -import com.evolveum.midpoint.web.component.form.DropDownFormGroup; -import com.evolveum.midpoint.web.component.input.QNameObjectTypeChoiceRenderer; -import com.evolveum.midpoint.web.component.input.RelationDropDownChoicePanel; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; -import com.evolveum.midpoint.web.component.search.Search; -import com.evolveum.midpoint.web.component.search.SearchFactory; -import com.evolveum.midpoint.web.component.util.EnableBehaviour; -import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; -import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.component.ChooseTypePanel; -import com.evolveum.midpoint.web.page.admin.dto.ObjectViewDto; -import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; -import com.evolveum.midpoint.web.session.UserProfileStorage.TableId; - -import org.apache.wicket.model.StringResourceModel; - -import static com.evolveum.midpoint.web.component.data.column.ColumnUtils.createStringResource; - -public abstract class AbstractRoleMemberPanel extends BasePanel { - - private static final long serialVersionUID = 1L; - - protected enum QueryScope { - SELECTED, ALL, ALL_DIRECT - } - - protected enum MemberOperation { - ADD, REMOVE, RECOMPUTE - } - - private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMemberPanel.class); - private static final String DOT_CLASS = AbstractRoleMemberPanel.class.getName() + "."; - protected static final String OPERATION_LOAD_MEMBER_RELATIONS = DOT_CLASS + "loadMemberRelationsList"; - protected static final String OPERATION_LOAD_ARCHETYPE_OBJECT = DOT_CLASS + "loadArchetypeObject"; - - protected static final String ID_FORM = "form"; - - protected static final String ID_CONTAINER_MEMBER = "memberContainer"; - protected static final String ID_CHILD_TABLE = "childUnitTable"; - protected static final String ID_MEMBER_TABLE = "memberTable"; - - private static final String ID_OBJECT_TYPE = "type"; - private static final String ID_TENANT = "tenant"; - private static final String ID_PROJECT = "project"; - private static final String ID_INDIRECT_MEMBERS = "indirectMembers"; - - protected static final String ID_SEARCH_SCOPE = "searchScope"; - protected SearchBoxScopeType scopeDefaultValue = null; - protected QName objectTypeDefaultValue = null; - - protected static final String ID_SEARCH_BY_RELATION = "searchByRelation"; - - private static Map> authorizations = new HashMap<>(); - private static Map tablesId = new HashMap<>(); - - static { - tablesId.put(RoleType.COMPLEX_TYPE, TableId.ROLE_MEMEBER_PANEL); - tablesId.put(ServiceType.COMPLEX_TYPE, TableId.SERVICE_MEMEBER_PANEL); - tablesId.put(OrgType.COMPLEX_TYPE, TableId.ORG_MEMEBER_PANEL); - tablesId.put(ArchetypeType.COMPLEX_TYPE, TableId.ARCHETYPE_MEMEBER_PANEL); - } - - static { - authorizations.put(RoleType.COMPLEX_TYPE, GuiAuthorizationConstants.ROLE_MEMBERS_AUTHORIZATIONS); - authorizations.put(ServiceType.COMPLEX_TYPE, GuiAuthorizationConstants.SERVICE_MEMBERS_AUTHORIZATIONS); - authorizations.put(OrgType.COMPLEX_TYPE, GuiAuthorizationConstants.ORG_MEMBERS_AUTHORIZATIONS); - authorizations.put(ArchetypeType.COMPLEX_TYPE, GuiAuthorizationConstants.ARCHETYPE_MEMBERS_AUTHORIZATIONS); - } - - public AbstractRoleMemberPanel(String id, IModel model) { - super(id, model); - } - - @Override - protected void onInitialize(){ - super.onInitialize(); - initLayout(); - } - - protected void initLayout() { - Form form = new com.evolveum.midpoint.web.component.form.Form(ID_FORM); - form.setOutputMarkupId(true); - add(form); - initDefaultSearchParameters(); - initSearch(form); - initMemberTable(form); - setOutputMarkupId(true); - - } - - private void initDefaultSearchParameters(){ - GuiObjectListPanelConfigurationType additionalPanel = getAdditionalPanelConfig(); - if (additionalPanel != null && additionalPanel.getSearchBoxConfiguration() != null) { - scopeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultScope(); - objectTypeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultObjectType(); - } - if (scopeDefaultValue == null){ - scopeDefaultValue = SearchBoxScopeType.ONE_LEVEL; - } - if (objectTypeDefaultValue == null){ - objectTypeDefaultValue = WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType()); - } - if (getMemberPanelStorage() != null){ - if (getMemberPanelStorage().getOrgSearchScope() == null){ - getMemberPanelStorage().setOrgSearchScope(scopeDefaultValue); - } - if (getMemberPanelStorage().getType() == null){ - getMemberPanelStorage().setType(ObjectTypes.getObjectType(objectTypeDefaultValue.getLocalPart())); - } - } - } - - protected Form getForm() { - return (Form) get(ID_FORM); - } - - private void initMemberTable(Form form) { - WebMarkupContainer memberContainer = new WebMarkupContainer(ID_CONTAINER_MEMBER); - memberContainer.setOutputMarkupId(true); - memberContainer.setOutputMarkupPlaceholderTag(true); - form.add(memberContainer); - - PageBase pageBase = getPageBase(); - Class type = getMemberPanelStorage() != null && getMemberPanelStorage().getType() != null ? - getMemberPanelStorage().getType().getClassDefinition() : ObjectType.class; - //TODO QName defines a relation value which will be used for new member creation - MainObjectListPanel childrenListPanel = new MainObjectListPanel( - ID_MEMBER_TABLE, type, getTableId(getComplexTypeQName()), getSearchOptions()) { - - private static final long serialVersionUID = 1L; - - @Override - protected void objectDetailsPerformed(AjaxRequestTarget target, ObjectType object) { - detailsPerformed(target, object); - } - - @Override - protected boolean isObjectDetailsEnabled(IModel> rowModel) { - if (rowModel == null || rowModel.getObject() == null - || rowModel.getObject().getValue() == null) { - return false; - } - Class objectClass = rowModel.getObject().getValue().getClass(); - return WebComponentUtil.hasDetailsPage(objectClass); - } - - @Override - protected DisplayType getNewObjectButtonSpecialDisplayType(){ - return getCreateMemberButtonDisplayType(); - } - - @Override - protected DisplayType getNewObjectButtonStandardDisplayType(){ - return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", - createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); - } - - @Override - protected List loadButtonDescriptions() { - return createAdditionalButtonsDescription(); - } - - @Override - protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { - AbstractRoleMemberPanel.this.createFocusMemberPerformed(target, relation); - } - - @Override - protected List createToolbarButtonsList(String buttonId){ - List buttonsList = super.createToolbarButtonsList(buttonId); - MultifunctionalButton assignButton = createAssignButton(buttonId); - buttonsList.add(1, assignButton); - return buttonsList; - } - - @Override - protected IColumn, String> createIconColumn(){ - return (IColumn) ColumnUtils.createIconColumn(pageBase); - } - - @Override - protected List, String>> createColumns() { - return createMembersColumns(); - } - - @Override - protected List createInlineMenu() { - return createRowActions(); - } - - @Override - protected Search createSearch() { - return getMemberPanelStorage() != null && getMemberPanelStorage().getSearch() != null ? - getMemberPanelStorage().getSearch() : SearchFactory.createSearch(getDefaultObjectType(), pageBase); - } - - @Override - protected ObjectQuery createContentQuery() { - ObjectQuery q = super.createContentQuery(); - - ObjectQuery members = AbstractRoleMemberPanel.this.createContentQuery(); - - List filters = new ArrayList<>(); - - if (q != null && q.getFilter() != null) { - filters.add(q.getFilter()); - } - - if (members != null && members.getFilter() != null) { - filters.add(members.getFilter()); - } - - QueryFactory queryFactory = pageBase.getPrismContext().queryFactory(); - if (filters.size() == 1) { - return queryFactory.createQuery(filters.iterator().next()); - } else { - return queryFactory.createQuery(queryFactory.createAnd(filters)); - } - } - - @Override - protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ - return AbstractRoleMemberPanel.this.getAdditionalPanelConfig(); - } - - @Override - protected boolean isAdditionalPanel(){ - return true; - } - - protected boolean isTypeChanged(Class newTypeClass){ - return true; - } - }; - childrenListPanel.setOutputMarkupId(true); - memberContainer.add(childrenListPanel); - } - - private List createAdditionalButtonsDescription() { - List multiFunctinalButtonDtos = new ArrayList<>(); - List loadedRelations = loadMemberRelationsList(); - if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(loadedRelations)) { - List relations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadedRelations); - relations.forEach(relation -> { - MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); - DisplayType additionalButtonDisplayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(getPageBase(), relation, - "abstractRoleMemberPanel.menu.createMember"); - buttonDto.setAdditionalButtonDisplayType(additionalButtonDisplayType); - buttonDto.setCompositedIcon(createCompositedIcon(relation, additionalButtonDisplayType)); - buttonDto.setAssignmentObjectRelation(relation); - multiFunctinalButtonDtos.add(buttonDto); - }); - } - return multiFunctinalButtonDtos; - } - - private CompositedIcon createCompositedIcon(AssignmentObjectRelation relation, DisplayType additionalButtonDisplayType) { - CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(getPageBase(), relation, - additionalButtonDisplayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green")); - if (builder == null) { - return null; - } - return builder.build(); - } - - private MultifunctionalButton createAssignButton(String buttonId) { - MultifunctionalButton assignButton = new MultifunctionalButton(buttonId, createAssignmentAdditionalButtons()) { - private static final long serialVersionUID = 1L; - - - @Override - protected void buttonClickPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { - List relations = relation != null && !CollectionUtils.isEmpty(relation.getRelations()) ? - Arrays.asList(relation.getRelations().get(0)) : getSupportedRelations().getAvailableRelationList(); - AvailableRelationDto avariableRelations = new AvailableRelationDto(relations, getSupportedRelations().getDefaultRelation()); - List objectTypes = relation != null && !CollectionUtils.isEmpty(relation.getObjectTypes()) ? - relation.getObjectTypes() : null; - List archetypeRefList = relation != null && !CollectionUtils.isEmpty(relation.getArchetypeRefs()) ? - relation.getArchetypeRefs() : null; - assignMembers(target, avariableRelations, objectTypes, archetypeRefList, relation == null); - } - - @Override - protected DisplayType getMainButtonDisplayType(){ - return getAssignMemberButtonDisplayType(); - } - - @Override - protected DisplayType getDefaultObjectButtonDisplayType(){ - return getAssignMemberButtonDisplayType(); - } - - }; - assignButton.add(AttributeAppender.append("class", "btn-margin-right")); - - - return assignButton; - } - - private List createAssignmentAdditionalButtons() { - List additionalAssignmentButtons = new ArrayList<>(); - List assignmentObjectRelations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadMemberRelationsList()); - if (assignmentObjectRelations == null) { - return additionalAssignmentButtons; - } - assignmentObjectRelations.forEach(relation -> { - MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); - buttonDto.setAssignmentObjectRelation(relation); - - DisplayType additionalDispayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(AbstractRoleMemberPanel.this.getPageBase(), relation, - "abstractRoleMemberPanel.menu.assignMember"); - //TODO null additinalDisplayType - CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(AbstractRoleMemberPanel.this.getPageBase(), relation, - additionalDispayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green")); - CompositedIcon icon = builder.build(); - buttonDto.setAdditionalButtonDisplayType(additionalDispayType); - buttonDto.setCompositedIcon(icon); - additionalAssignmentButtons.add(buttonDto); - }); - - return additionalAssignmentButtons; - - } - - protected TableId getTableId(QName complextType) { - return tablesId.get(complextType); - } - - protected Map getAuthorizations(QName complexType) { - return authorizations.get(complexType); - } - - protected QName getComplexTypeQName() { - return getModelObject().asPrismObject().getComplexTypeDefinition().getTypeName(); - } - - private DisplayType getCreateMemberButtonDisplayType(){ - return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", - AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); - } - - private DisplayType getAssignMemberButtonDisplayType(){ - return WebComponentUtil.createDisplayType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green", - AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.assignMember", "", "").getString()); - } - - protected List createRowActions() { - List menu = new ArrayList<>(); - createAssignMemberRowAction(menu); - - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_UNASSIGN)) { - menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.unassign")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - unassignMembersPerformed(target); - } - }; - - } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_UNASSIGN; - } - }); - } - - createRecomputeMemberRowAction(menu); - - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_CREATE)) { - menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.create")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - createFocusMemberPerformed(target); - } - }; - } - }); - } - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_DELETE)) { - menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.delete")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - deleteMembersPerformed(target); - } - }; - } - - }); - } - return menu; - } - - protected void createAssignMemberRowAction(List menu) { - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_ASSIGN)) { - menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.assign")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - MemberOperationsHelper.assignMembers(getPageBase(), AbstractRoleMemberPanel.this.getModelObject(), target, getSupportedRelations(), null); - } - }; - } - }); - } - } - - protected void createRecomputeMemberRowAction(List menu) { - if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_RECOMPUTE)) { - menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.recompute")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new HeaderMenuAction(AbstractRoleMemberPanel.this) { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - recomputeMembersPerformed(target); - } - }; - } - -// @Override -// public IModel getConfirmationMessageModel() { -// return getMemberTable().getSelectedObjectsCount() > 0 ? -// createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") -// : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); -// } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_RECONCILE_MENU_ITEM; - } - - }); - } - } - - - - protected abstract AvailableRelationDto getSupportedRelations(); - - protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ - return null; - } - - private boolean isAuthorized(String action) { - Map memeberAuthz = getAuthorizations(getComplexTypeQName()); - return WebComponentUtil.isAuthorized(memeberAuthz.get(action)); - } - - - - private List loadMemberRelationsList(){ - List assignmentTargetRelations = new ArrayList<>(); - AssignmentCandidatesSpecification spec = loadCandidateSpecification(); - assignmentTargetRelations = spec != null ? spec.getAssignmentObjectRelations() : new ArrayList<>(); - return assignmentTargetRelations; - } - - private AssignmentCandidatesSpecification loadCandidateSpecification(){ - OperationResult result = new OperationResult(OPERATION_LOAD_MEMBER_RELATIONS); - PrismObject obj = getModelObject().asPrismObject(); - AssignmentCandidatesSpecification spec = null; - try { - spec = getPageBase().getModelInteractionService() - .determineAssignmentHolderSpecification(obj, result); - } catch (SchemaException | ConfigurationException ex){ - result.recordPartialError(ex.getLocalizedMessage()); - LOGGER.error("Couldn't load member relations list for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); - } - return spec; - } - - protected void assignMembers(AjaxRequestTarget target, AvailableRelationDto availableRelationList, - List objectTypes, List archetypeRefList, boolean isOrgTreePanelVisible) { - MemberOperationsHelper.assignMembers(getPageBase(), getModelObject(), target, availableRelationList, - objectTypes, archetypeRefList, isOrgTreePanelVisible); - } - - private void unassignMembersPerformed(AjaxRequestTarget target) { - QueryScope scope = getQueryScope(false); - - ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), - createStringResource("abstractRoleMemberPanel.unassignAllMembersConfirmationLabel")) { - private static final long serialVersionUID = 1L; - - @Override - protected List getSupportedObjectTypes() { - return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); - } - - @Override - protected List getSupportedRelations() { - return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); - } - - @Override - protected boolean isFocusTypeSelectorVisible() { - return !QueryScope.SELECTED.equals(scope); - } - - - protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { - unassignMembersPerformed(type, scope, relations, target); - } - - @Override - protected QName getDefaultObjectType() { - return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), - AbstractRoleMemberPanel.this.getDefaultObjectType()); - } - }; - - getPageBase().showMainPopup(chooseTypePopupContent, target); - } - - private void deleteMembersPerformed(AjaxRequestTarget target) { - QueryScope scope = getQueryScope(false); - ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), - createStringResource("abstractRoleMemberPanel.deleteAllMembersConfirmationLabel")) { - private static final long serialVersionUID = 1L; - - @Override - protected List getSupportedObjectTypes() { - return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); - } - - @Override - protected List getSupportedRelations() { - return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); - } - - protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { - deleteMembersPerformed(type, scope, relations, target); - - } - - @Override - protected boolean isFocusTypeSelectorVisible() { - return !QueryScope.SELECTED.equals(scope); - } - - @Override - protected QName getDefaultObjectType() { - return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), - AbstractRoleMemberPanel.this.getDefaultObjectType()); - } - - }; - - getPageBase().showMainPopup(chooseTypePopupContent, target); - - } - - protected void createFocusMemberPerformed(AjaxRequestTarget target) { - createFocusMemberPerformed(target, null); - } - - protected void createFocusMemberPerformed(AjaxRequestTarget target, AssignmentObjectRelation relationSpec) { - if (relationSpec != null){ - try { - List newReferences = new ArrayList<>(); - if (CollectionUtils.isEmpty(relationSpec.getRelations())){ - relationSpec.setRelations(Arrays.asList(RelationTypes.MEMBER.getRelation())); - } - ObjectReferenceType memberRef = ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relationSpec.getRelations().get(0)); - newReferences.add(memberRef); - if (CollectionUtils.isNotEmpty(relationSpec.getArchetypeRefs())) { - newReferences.add(relationSpec.getArchetypeRefs().get(0)); - } - QName newMemberType = CollectionUtils.isNotEmpty(relationSpec.getObjectTypes()) ? relationSpec.getObjectTypes().get(0) : - getSupportedObjectTypes(false).get(0); - WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), newMemberType, newReferences); - } catch (SchemaException e) { - throw new SystemException(e.getMessage(), e); - } - } else { - ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel( - getPageBase().getMainPopupBodyId()) { - private static final long serialVersionUID = 1L; - - @Override - protected List getSupportedObjectTypes() { - return AbstractRoleMemberPanel.this.getNewMemberObjectTypes(); - } - - @Override - protected List getSupportedRelations() { - return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); - } - - protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { - if (type == null) { - getSession().warn("No type was selected. Cannot create member"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - if (relations == null || relations.isEmpty()) { - getSession().warn("No relation was selected. Cannot create member"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - AbstractRoleMemberPanel.this.getPageBase().hideMainPopup(target); - try { - List newReferences = new ArrayList<>(); - for (QName relation : relations) { - newReferences.add(ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relation)); - } - WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), type, newReferences); - } catch (SchemaException e) { - throw new SystemException(e.getMessage(), e); - } - - } - - @Override - protected QName getDefaultObjectType() { - if (relationSpec != null && CollectionUtils.isNotEmpty(relationSpec.getObjectTypes())) { - return relationSpec.getObjectTypes().get(0); - } - return super.getDefaultObjectType(); - } - - @Override - protected boolean isFocusTypeSelectorVisible() { - return relationSpec == null; - } - }; - - getPageBase().showMainPopup(chooseTypePopupContent, target); - } - } - - protected void deleteMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { - if (relations == null || relations.isEmpty()) { - getSession().warn("No relation was selected. Cannot perform delete members"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - MemberOperationsHelper.deleteMembersPerformed(getPageBase(), scope, getActionQuery(scope, relations), type, target); - } - - protected void unassignMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { - if (relations == null || relations.isEmpty()) { - getSession().warn("No relation was selected. Cannot perform unassign members"); - target.add(this); - target.add(getPageBase().getFeedbackPanel()); - return; - } - MemberOperationsHelper.unassignMembersPerformed(getPageBase(), getModelObject(), scope, getActionQuery(scope, relations), relations, type, target); - } - - private ObjectViewDto getParameter(String panelId) { - ChooseTypePanel tenantChoice = (ChooseTypePanel) get(createComponentPath(ID_FORM, panelId)); - return tenantChoice.getModelObject(); - } - - protected ObjectQuery getActionQuery(QueryScope scope, Collection relations) { - switch (scope) { - case ALL: - return createAllMemberQuery(relations); - case ALL_DIRECT: - return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); - case SELECTED: - return MemberOperationsHelper.createSelectedObjectsQuery(getMemberTable().getSelectedObjects(), getPrismContext()); - } - - return null; - } - - protected void initSearch(Form form) { - - List scopeValues = Arrays.asList(SearchBoxScopeType.values()); - DropDownFormGroup searchScrope = createDropDown(ID_SEARCH_SCOPE, - Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getOrgSearchScope() : scopeDefaultValue), - scopeValues, - WebComponentUtil.getEnumChoiceRenderer(AbstractRoleMemberPanel.this), - "abstractRoleMemberPanel.searchScope", "abstractRoleMemberPanel.searchScope.tooltip", true); - searchScrope.add(new VisibleBehaviour(() -> getModelObject() instanceof OrgType)); - form.add(searchScrope); - - List supportedTypes = getSupportedObjectTypes(false); - DropDownFormGroup typeSelect = createDropDown(ID_OBJECT_TYPE, - Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType())), - supportedTypes, new QNameObjectTypeChoiceRenderer(){ - private static final long serialVersionUID = 1L; - - @Override - public Object getDisplayValue(QName qname) { - if (qname == null || getObjectTypesListParentType().equals(qname)){ - return StringUtils.leftPad(createStringResource("ObjectTypes.all").getString(), 1); - } else { - return super.getDisplayValue(qname); - } - } - - @Override - public QName getObject(String id, IModel> choices) { - QName qname = super.getObject(id, choices); - if (qname == null){ - return getObjectTypesListParentType(); - } - return qname; - } - - }, - "abstractRoleMemberPanel.type", "abstractRoleMemberPanel.type.tooltip", false); - form.add(typeSelect); - - RelationDropDownChoicePanel relationSelector = new RelationDropDownChoicePanel(ID_SEARCH_BY_RELATION, - getMemberPanelStorage() != null ? getMemberPanelStorage().getRelation() : getSupportedRelations().getDefaultRelation(), - getSupportedRelations().getAvailableRelationList(), true){ - private static final long serialVersionUID = 1L; - - @Override - protected void onValueChanged(AjaxRequestTarget target){ - refreshAll(target); - } - - @Override - protected String getNullValidDisplayValue(){ - return getString("RelationTypes.ANY"); - } - }; - form.add(relationSelector); - - ChooseTypePanel tenant = createParameterPanel(ID_TENANT, true); - form.add(tenant); - tenant.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); - - ChooseTypePanel project = createParameterPanel(ID_PROJECT, false); - form.add(project); - project.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); - - CheckFormGroup includeIndirectMembers = new CheckFormGroup(ID_INDIRECT_MEMBERS, - Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getIndirect() : false), - createStringResource("abstractRoleMemberPanel.indirectMembers"), "abstractRoleMemberPanel.indirectMembers.tooltip", false, "col-md-4", "col-md-2"); - includeIndirectMembers.getCheck().add(new AjaxFormComponentUpdatingBehavior("change") { - - private static final long serialVersionUID = 1L; - - protected void onUpdate(AjaxRequestTarget target) { - refreshAll(target); - }; - - }); - - includeIndirectMembers.getCheck().add(new EnableBehaviour(() -> - getSearchScopeValue().equals(SearchBoxScopeType.ONE_LEVEL) || !searchScrope.isVisible())); - includeIndirectMembers.setOutputMarkupId(true); - form.add(includeIndirectMembers); - - } - - protected List getSupportedObjectTypes(boolean includeAbstractTypes) { - return WebComponentUtil.createFocusTypeList(includeAbstractTypes); - } - - protected QName getObjectTypesListParentType(){ - return FocusType.COMPLEX_TYPE; - } - - protected List getNewMemberObjectTypes() { - return WebComponentUtil.createFocusTypeList(); - } - - private ChooseTypePanel createParameterPanel(String id, boolean isTenant) { - - ChooseTypePanel orgSelector = new ChooseTypePanel(id, Model.of(new ObjectViewDto())) { - - private static final long serialVersionUID = 1L; - - @Override - protected void executeCustomAction(AjaxRequestTarget target, OrgType object) { - refreshAll(target); - } - - @Override - protected void executeCustomRemoveAction(AjaxRequestTarget target) { - refreshAll(target); - } - - @Override - protected ObjectQuery getChooseQuery() { - S_FilterEntryOrEmpty q = getPrismContext().queryFor(OrgType.class); - if (isTenant) { - return q.item(OrgType.F_TENANT).eq(true).build(); - } else { - return q.not().item(OrgType.F_TENANT).eq(true).build(); - } - } - - @Override - protected boolean isSearchEnabled() { - return true; - } - - @Override - public Class getObjectTypeClass() { - return OrgType.class; - } - - @Override - protected AttributeAppender getInputStyleClass(){ - return AttributeAppender.append("class", "col-md-10"); - } - - }; - orgSelector.setOutputMarkupId(true); - orgSelector.setOutputMarkupPlaceholderTag(true); - return orgSelector; - - } - - private DropDownFormGroup createDropDown(String id, IModel defaultModel, final List values, - IChoiceRenderer renderer, String labelKey, String tooltipKey, boolean required) { - DropDownFormGroup listSelect = new DropDownFormGroup(id, defaultModel, Model.ofList(values), renderer, createStringResource(labelKey), - tooltipKey, false, "col-md-4", "col-md-8", required){ - private static final long serialVersionUID = 1L; - - @Override - protected String getNullValidDisplayValue(){ - return getString("ObjectTypes.all"); - } - }; - - listSelect.getInput().add(new OnChangeAjaxBehavior() { - private static final long serialVersionUID = 1L; - - @Override - protected void onUpdate(AjaxRequestTarget target) { - refreshAll(target); - } - }); - listSelect.setOutputMarkupId(true); - return listSelect; - } - - protected void refreshAll(AjaxRequestTarget target) { - updateMembersPanelSessionStorage(); - - DropDownFormGroup typeChoice = (DropDownFormGroup) get(createComponentPath(ID_FORM, ID_OBJECT_TYPE)); - QName type = getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : typeChoice.getModelObject(); - getMemberTable().clearCache(); - getMemberTable().refreshTable(WebComponentUtil.qnameToClass(getPrismContext(), type, FocusType.class), target); - target.add(this); - } - - - private MainObjectListPanel getMemberTable() { - return (MainObjectListPanel) get(createComponentPath(ID_FORM, ID_CONTAINER_MEMBER, ID_MEMBER_TABLE)); - } - - protected QueryScope getQueryScope(boolean isRecompute) { - if (CollectionUtils.isNotEmpty(MemberOperationsHelper.getFocusOidToRecompute(getMemberTable().getSelectedObjects()))) { - return QueryScope.SELECTED; - } - - if (getIndirectmembersPanel().getValue()) { - return QueryScope.ALL; - } - - return QueryScope.ALL_DIRECT; - } - - private CheckFormGroup getIndirectmembersPanel() { - return (CheckFormGroup) get(createComponentPath(ID_FORM, ID_INDIRECT_MEMBERS)); - } - - protected void recomputeMembersPerformed(AjaxRequestTarget target) { - - StringResourceModel confirmModel = getMemberTable().getSelectedObjectsCount() > 0 ? - createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") - : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); - - ConfigureTaskConfirmationPanel dialog = new ConfigureTaskConfirmationPanel(((PageBase)getPage()).getMainPopupBodyId(), - confirmModel) { - - private static final long serialVersionUID = 1L; - - @Override - protected PrismObject getTask(AjaxRequestTarget target) { - Task task = MemberOperationsHelper.createRecomputeMembersTask(getPageBase(), getQueryScope(true), - getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); - return task.getClonedTaskObject(); - } - - @Override - public StringResourceModel getTitle() { - return createStringResource("pageUsers.message.confirmActionPopupTitle"); - } - - @Override - public void yesPerformed(AjaxRequestTarget target) { - MemberOperationsHelper.recomputeMembersPerformed(getPageBase(), getQueryScope(true), - getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); - } - }; - ((PageBase)getPage()).showMainPopup(dialog, target); - } - - protected ObjectQuery createContentQuery() { - CheckFormGroup isIndirect = getIndirectmembersPanel(); - List relations = QNameUtil.match(getSelectedRelation(), PrismConstants.Q_ANY) ? getSupportedRelations().getAvailableRelationList() : Arrays.asList(getSelectedRelation()); - return createMemberQuery(isIndirect != null ? isIndirect.getValue() : false, relations); - - } - - protected QName getSelectedRelation(){ - MemberPanelStorage storage = getMemberPanelStorage(); - if (storage != null){ - return storage.getRelation(); - } - RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); - return relationDropDown.getRelationValue(); - } - - private SearchBoxScopeType getSearchScopeValue(){ - if (getMemberPanelStorage() != null){ - return getMemberPanelStorage().getOrgSearchScope(); - } - DropDownFormGroup searchScopeComponent = (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); - return searchScopeComponent.getModelObject(); - } - - protected ObjectTypes getSearchType() { - DropDownFormGroup searchByTypeChoice = (DropDownFormGroup) get( - createComponentPath(ID_FORM, ID_OBJECT_TYPE)); - QName typeName = searchByTypeChoice.getModelObject(); - return ObjectTypes.getObjectTypeFromTypeQName(typeName); - } - - protected ObjectQuery createMemberQuery(boolean indirect, Collection relations) { - if (indirect) { - return createAllMemberQuery(relations); - } - - return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); - } - - - protected ObjectQuery createAllMemberQuery(Collection relations) { - return getPrismContext().queryFor(FocusType.class) - .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(MemberOperationsHelper.createReferenceValuesList(getModelObject(), relations)) - .build(); - } - - - protected ObjectReferenceType createReference() { - ObjectReferenceType ref = ObjectTypeUtil.createObjectRef(getModelObject(), getPageBase().getPrismContext()); - return ref; - } - - protected void detailsPerformed(AjaxRequestTarget target, ObjectType object) { - if (WebComponentUtil.hasDetailsPage(object.getClass())) { - WebComponentUtil.dispatchToObjectDetailsPage(object.getClass(), object.getOid(), this, true); - } else { - error("Could not find proper response page"); - throw new RestartResponseException(getPageBase()); - } - } - - protected List, String>> createMembersColumns() { - List, String>> columns = new ArrayList<>(); - - IColumn, String> column = new AbstractExportableColumn, String>( - createStringResource("TreeTablePanel.fullName.displayName")) { - private static final long serialVersionUID = 1L; - - @Override - public void populateItem(Item>> cellItem, - String componentId, IModel> rowModel) { - SelectableBean bean = rowModel.getObject(); - ObjectType object = bean.getValue(); - cellItem.add(new Label(componentId, - getMemberObjectDisplayName(object, true))); - } - - @Override - public IModel getDataModel(IModel> rowModel) { - return Model.of(getMemberObjectDisplayName(rowModel.getObject().getValue(), true)); - } - - }; - columns.add(column); - - column = new AbstractExportableColumn, String>( - createStringResource("TreeTablePanel.identifier.description")) { - private static final long serialVersionUID = 1L; - - @Override - public void populateItem(Item>> cellItem, - String componentId, IModel> rowModel) { - SelectableBean bean = rowModel.getObject(); - ObjectType object = bean.getValue(); - cellItem.add(new Label(componentId, getMemberObjectIdentifier(object))); - } - - @Override - public IModel getDataModel(IModel> rowModel) { - return Model.of(getMemberObjectIdentifier(rowModel.getObject().getValue())); - } - - }; - columns.add(column); -// if (isRelationColumnVisible()){ - columns.add(createRelationColumn()); -// } - return columns; - } - - protected IColumn, String> createRelationColumn() { - return new AbstractExportableColumn, String>( - createStringResource("roleMemberPanel.relation")) { - private static final long serialVersionUID = 1L; - - @Override - public void populateItem(Item>> cellItem, - String componentId, IModel> rowModel) { - cellItem.add(new Label(componentId, - getRelationValue(rowModel.getObject().getValue()))); - } - - @Override - public IModel getDataModel(IModel> rowModel) { - return Model.of(getRelationValue(rowModel.getObject().getValue())); - } - - }; - } - - protected boolean isRelationColumnVisible(){ - return false; - } - - - private String getMemberObjectDisplayName(ObjectType object){ - return getMemberObjectDisplayName(object, false); - } - - private String getMemberObjectDisplayName(ObjectType object, boolean translate){ - if (object == null){ - return ""; - } - if (object instanceof UserType) { - return WebComponentUtil.getTranslatedPolyString(((UserType) object).getFullName()); - } else if (object instanceof AbstractRoleType) { - return WebComponentUtil.getTranslatedPolyString(((AbstractRoleType) object).getDisplayName()); - } else { - return ""; - } - } - - private String getMemberObjectIdentifier(ObjectType object){ - if (object == null){ - return ""; - } - if (object instanceof UserType) { - return ((UserType) object).getEmailAddress(); - } else if (object instanceof AbstractRoleType) { - return ((AbstractRoleType) object).getIdentifier(); - } else { - return object.getDescription(); - } - } - - private Collection> getSearchOptions(){ - return SelectorOptions - .createCollection(GetOperationOptions.createDistinct()); - } - - protected Class getDefaultObjectType(){ - return (Class) FocusType.class; - } - - protected Form getFormComponent(){ - return (Form) get(ID_FORM); - } - - - private String getRelationValue(ObjectType focusObject){ - String relation = ""; - if (FocusType.class.isAssignableFrom(focusObject.getClass())) { - // Do NOT take relation from an assignment. Use roleMembershipRef instead. Reasons: - // 1. Authorizations (MID-4893). User may be authorized just for roleMemberhsipRef and not for assignment - // Authorization for roleMembershipRef is enough to display member panel. - // 2. There may be assignments that are not valid. We do not want to display relation for those. - for (ObjectReferenceType roleMembershipRef : getMembershipReferenceList((FocusType) focusObject)) { - relation = buildRelation(roleMembershipRef, relation); - } - - } - return relation; - - } - - protected List getMembershipReferenceList(FocusType focusObject){ - return focusObject.getRoleMembershipRef(); - } - - private String buildRelation(ObjectReferenceType roleMembershipRef, String relation) { - if (roleMembershipRef.getOid().equals(getModelObject().getOid())) { - QName assignmentRelation = roleMembershipRef.getRelation(); - if (getSupportedRelations().getAvailableRelationList().stream().anyMatch(r -> QNameUtil.match(r, assignmentRelation))) { - if (!StringUtils.isBlank(relation)) { - relation += ","; - } - relation += assignmentRelation.getLocalPart(); - } - } - return relation; - } - - protected void updateMembersPanelSessionStorage(){ - MemberPanelStorage storage = getMemberPanelStorage(); - if (storage != null){ - storage.setType(getSearchType()); - - RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); - storage.setRelation(relationDropDown.getRelationValue()); - - CheckFormGroup indirectPanel = getIndirectmembersPanel(); - if (indirectPanel != null){ - storage.setIndirect(indirectPanel.getValue()); - } - - DropDownFormGroup searchScopeComponent = - (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); - storage.setOrgSearchScope(searchScopeComponent.getModelObject()); - } - } - - protected MemberPanelStorage getMemberPanelStorage(){ - return null; - } -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ +package com.evolveum.midpoint.web.page.admin.roles; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.xml.namespace.QName; + +import com.evolveum.midpoint.gui.impl.component.icon.CompositedIcon; +import com.evolveum.midpoint.gui.impl.component.icon.CompositedIconBuilder; +import com.evolveum.midpoint.model.api.AssignmentCandidatesSpecification; +import com.evolveum.midpoint.model.api.AssignmentObjectRelation; +import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.polystring.PolyString; +import com.evolveum.midpoint.prism.query.QueryFactory; +import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty; +import com.evolveum.midpoint.schema.constants.RelationTypes; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.exception.ConfigurationException; +import com.evolveum.midpoint.web.component.MultiFunctinalButtonDto; +import com.evolveum.midpoint.web.component.MultifunctionalButton; +import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; +import com.evolveum.midpoint.web.component.data.column.ColumnUtils; +import com.evolveum.midpoint.web.component.dialog.ConfigureTaskConfirmationPanel; +import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; +import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; +import com.evolveum.midpoint.web.component.util.SelectableBean; +import com.evolveum.midpoint.web.page.admin.configuration.component.HeaderMenuAction; +import com.evolveum.midpoint.web.session.MemberPanelStorage; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; +import org.apache.commons.collections.CollectionUtils; +import org.apache.commons.lang.StringUtils; +import org.apache.wicket.Component; +import org.apache.wicket.RestartResponseException; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.ajax.form.AjaxFormComponentUpdatingBehavior; +import org.apache.wicket.ajax.form.OnChangeAjaxBehavior; +import org.apache.wicket.behavior.AttributeAppender; +import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; +import org.apache.wicket.markup.html.WebMarkupContainer; +import org.apache.wicket.markup.html.basic.Label; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.markup.html.form.IChoiceRenderer; +import org.apache.wicket.markup.repeater.Item; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.Model; + +import com.evolveum.midpoint.gui.api.GuiStyleConstants; +import com.evolveum.midpoint.gui.api.component.BasePanel; +import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; +import com.evolveum.midpoint.gui.api.page.PageBase; +import com.evolveum.midpoint.gui.api.util.WebComponentUtil; +import com.evolveum.midpoint.prism.PrismConstants; +import com.evolveum.midpoint.prism.query.ObjectFilter; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.GetOperationOptions; +import com.evolveum.midpoint.schema.SelectorOptions; +import com.evolveum.midpoint.schema.constants.ObjectTypes; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.util.QNameUtil; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SystemException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.dialog.ChooseFocusTypeAndRelationDialogPanel; +import com.evolveum.midpoint.web.component.form.CheckFormGroup; +import com.evolveum.midpoint.web.component.form.DropDownFormGroup; +import com.evolveum.midpoint.web.component.input.QNameObjectTypeChoiceRenderer; +import com.evolveum.midpoint.web.component.input.RelationDropDownChoicePanel; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; +import com.evolveum.midpoint.web.component.search.Search; +import com.evolveum.midpoint.web.component.search.SearchFactory; +import com.evolveum.midpoint.web.component.util.EnableBehaviour; +import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; +import com.evolveum.midpoint.web.component.util.VisibleBehaviour; +import com.evolveum.midpoint.web.page.admin.configuration.component.ChooseTypePanel; +import com.evolveum.midpoint.web.page.admin.dto.ObjectViewDto; +import com.evolveum.midpoint.web.security.GuiAuthorizationConstants; +import com.evolveum.midpoint.web.session.UserProfileStorage.TableId; + +import org.apache.wicket.model.StringResourceModel; + +import static com.evolveum.midpoint.web.component.data.column.ColumnUtils.createStringResource; + +public abstract class AbstractRoleMemberPanel extends BasePanel { + + private static final long serialVersionUID = 1L; + + protected enum QueryScope { + SELECTED, ALL, ALL_DIRECT + } + + protected enum MemberOperation { + ADD, REMOVE, RECOMPUTE + } + + private static final Trace LOGGER = TraceManager.getTrace(AbstractRoleMemberPanel.class); + private static final String DOT_CLASS = AbstractRoleMemberPanel.class.getName() + "."; + protected static final String OPERATION_LOAD_MEMBER_RELATIONS = DOT_CLASS + "loadMemberRelationsList"; + protected static final String OPERATION_LOAD_ARCHETYPE_OBJECT = DOT_CLASS + "loadArchetypeObject"; + + protected static final String ID_FORM = "form"; + + protected static final String ID_CONTAINER_MEMBER = "memberContainer"; + protected static final String ID_CHILD_TABLE = "childUnitTable"; + protected static final String ID_MEMBER_TABLE = "memberTable"; + + private static final String ID_OBJECT_TYPE = "type"; + private static final String ID_TENANT = "tenant"; + private static final String ID_PROJECT = "project"; + private static final String ID_INDIRECT_MEMBERS = "indirectMembers"; + + protected static final String ID_SEARCH_SCOPE = "searchScope"; + protected SearchBoxScopeType scopeDefaultValue = null; + protected QName objectTypeDefaultValue = null; + + protected static final String ID_SEARCH_BY_RELATION = "searchByRelation"; + + private static Map> authorizations = new HashMap<>(); + private static Map tablesId = new HashMap<>(); + + static { + tablesId.put(RoleType.COMPLEX_TYPE, TableId.ROLE_MEMEBER_PANEL); + tablesId.put(ServiceType.COMPLEX_TYPE, TableId.SERVICE_MEMEBER_PANEL); + tablesId.put(OrgType.COMPLEX_TYPE, TableId.ORG_MEMEBER_PANEL); + tablesId.put(ArchetypeType.COMPLEX_TYPE, TableId.ARCHETYPE_MEMEBER_PANEL); + } + + static { + authorizations.put(RoleType.COMPLEX_TYPE, GuiAuthorizationConstants.ROLE_MEMBERS_AUTHORIZATIONS); + authorizations.put(ServiceType.COMPLEX_TYPE, GuiAuthorizationConstants.SERVICE_MEMBERS_AUTHORIZATIONS); + authorizations.put(OrgType.COMPLEX_TYPE, GuiAuthorizationConstants.ORG_MEMBERS_AUTHORIZATIONS); + authorizations.put(ArchetypeType.COMPLEX_TYPE, GuiAuthorizationConstants.ARCHETYPE_MEMBERS_AUTHORIZATIONS); + } + + public AbstractRoleMemberPanel(String id, IModel model) { + super(id, model); + } + + @Override + protected void onInitialize(){ + super.onInitialize(); + initLayout(); + } + + protected void initLayout() { + Form form = new com.evolveum.midpoint.web.component.form.Form(ID_FORM); + form.setOutputMarkupId(true); + add(form); + initDefaultSearchParameters(); + initSearch(form); + initMemberTable(form); + setOutputMarkupId(true); + + } + + private void initDefaultSearchParameters(){ + GuiObjectListPanelConfigurationType additionalPanel = getAdditionalPanelConfig(); + if (additionalPanel != null && additionalPanel.getSearchBoxConfiguration() != null) { + scopeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultScope(); + objectTypeDefaultValue = additionalPanel.getSearchBoxConfiguration().getDefaultObjectType(); + } + if (scopeDefaultValue == null){ + scopeDefaultValue = SearchBoxScopeType.ONE_LEVEL; + } + if (objectTypeDefaultValue == null){ + objectTypeDefaultValue = WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType()); + } + if (getMemberPanelStorage() != null){ + if (getMemberPanelStorage().getOrgSearchScope() == null){ + getMemberPanelStorage().setOrgSearchScope(scopeDefaultValue); + } + if (getMemberPanelStorage().getType() == null){ + getMemberPanelStorage().setType(ObjectTypes.getObjectType(objectTypeDefaultValue.getLocalPart())); + } + } + } + + protected Form getForm() { + return (Form) get(ID_FORM); + } + + private void initMemberTable(Form form) { + WebMarkupContainer memberContainer = new WebMarkupContainer(ID_CONTAINER_MEMBER); + memberContainer.setOutputMarkupId(true); + memberContainer.setOutputMarkupPlaceholderTag(true); + form.add(memberContainer); + + PageBase pageBase = getPageBase(); + Class type = getMemberPanelStorage() != null && getMemberPanelStorage().getType() != null ? + getMemberPanelStorage().getType().getClassDefinition() : ObjectType.class; + //TODO QName defines a relation value which will be used for new member creation + MainObjectListPanel childrenListPanel = new MainObjectListPanel( + ID_MEMBER_TABLE, type, getTableId(getComplexTypeQName()), getSearchOptions()) { + + private static final long serialVersionUID = 1L; + + @Override + protected void objectDetailsPerformed(AjaxRequestTarget target, ObjectType object) { + detailsPerformed(target, object); + } + + @Override + protected boolean isObjectDetailsEnabled(IModel> rowModel) { + if (rowModel == null || rowModel.getObject() == null + || rowModel.getObject().getValue() == null) { + return false; + } + Class objectClass = rowModel.getObject().getValue().getClass(); + return WebComponentUtil.hasDetailsPage(objectClass); + } + + @Override + protected DisplayType getNewObjectButtonSpecialDisplayType(){ + return getCreateMemberButtonDisplayType(); + } + + @Override + protected DisplayType getNewObjectButtonStandardDisplayType(){ + return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", + createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); + } + + @Override + protected List loadButtonDescriptions() { + return createAdditionalButtonsDescription(); + } + + @Override + protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { + AbstractRoleMemberPanel.this.createFocusMemberPerformed(target, relation); + } + + @Override + protected List createToolbarButtonsList(String buttonId){ + List buttonsList = super.createToolbarButtonsList(buttonId); + MultifunctionalButton assignButton = createAssignButton(buttonId); + buttonsList.add(1, assignButton); + return buttonsList; + } + + @Override + protected IColumn, String> createIconColumn(){ + return (IColumn) ColumnUtils.createIconColumn(pageBase); + } + + @Override + protected List, String>> createColumns() { + return createMembersColumns(); + } + + @Override + protected List createInlineMenu() { + return createRowActions(); + } + + @Override + protected Search createSearch() { + return getMemberPanelStorage() != null && getMemberPanelStorage().getSearch() != null ? + getMemberPanelStorage().getSearch() : SearchFactory.createSearch(getDefaultObjectType(), pageBase); + } + + @Override + protected ObjectQuery createContentQuery() { + ObjectQuery q = super.createContentQuery(); + + ObjectQuery members = AbstractRoleMemberPanel.this.createContentQuery(); + + List filters = new ArrayList<>(); + + if (q != null && q.getFilter() != null) { + filters.add(q.getFilter()); + } + + if (members != null && members.getFilter() != null) { + filters.add(members.getFilter()); + } + + QueryFactory queryFactory = pageBase.getPrismContext().queryFactory(); + if (filters.size() == 1) { + return queryFactory.createQuery(filters.iterator().next()); + } else { + return queryFactory.createQuery(queryFactory.createAnd(filters)); + } + } + + @Override + protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ + return AbstractRoleMemberPanel.this.getAdditionalPanelConfig(); + } + + @Override + protected boolean isAdditionalPanel(){ + return true; + } + + protected boolean isTypeChanged(Class newTypeClass){ + return true; + } + }; + childrenListPanel.setOutputMarkupId(true); + memberContainer.add(childrenListPanel); + } + + private List createAdditionalButtonsDescription() { + List multiFunctinalButtonDtos = new ArrayList<>(); + List loadedRelations = loadMemberRelationsList(); + if (org.apache.commons.collections4.CollectionUtils.isNotEmpty(loadedRelations)) { + List relations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadedRelations); + relations.forEach(relation -> { + MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); + DisplayType additionalButtonDisplayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(getPageBase(), relation, + "abstractRoleMemberPanel.menu.createMember"); + buttonDto.setAdditionalButtonDisplayType(additionalButtonDisplayType); + buttonDto.setCompositedIcon(createCompositedIcon(relation, additionalButtonDisplayType)); + buttonDto.setAssignmentObjectRelation(relation); + multiFunctinalButtonDtos.add(buttonDto); + }); + } + return multiFunctinalButtonDtos; + } + + private CompositedIcon createCompositedIcon(AssignmentObjectRelation relation, DisplayType additionalButtonDisplayType) { + CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(getPageBase(), relation, + additionalButtonDisplayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green")); + if (builder == null) { + return null; + } + return builder.build(); + } + + private MultifunctionalButton createAssignButton(String buttonId) { + MultifunctionalButton assignButton = new MultifunctionalButton(buttonId, createAssignmentAdditionalButtons()) { + private static final long serialVersionUID = 1L; + + + @Override + protected void buttonClickPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { + List relations = relation != null && !CollectionUtils.isEmpty(relation.getRelations()) ? + Arrays.asList(relation.getRelations().get(0)) : getSupportedRelations().getAvailableRelationList(); + AvailableRelationDto avariableRelations = new AvailableRelationDto(relations, getSupportedRelations().getDefaultRelation()); + List objectTypes = relation != null && !CollectionUtils.isEmpty(relation.getObjectTypes()) ? + relation.getObjectTypes() : null; + List archetypeRefList = relation != null && !CollectionUtils.isEmpty(relation.getArchetypeRefs()) ? + relation.getArchetypeRefs() : null; + assignMembers(target, avariableRelations, objectTypes, archetypeRefList, relation == null); + } + + @Override + protected DisplayType getMainButtonDisplayType(){ + return getAssignMemberButtonDisplayType(); + } + + @Override + protected DisplayType getDefaultObjectButtonDisplayType(){ + return getAssignMemberButtonDisplayType(); + } + + }; + assignButton.add(AttributeAppender.append("class", "btn-margin-right")); + + + return assignButton; + } + + private List createAssignmentAdditionalButtons() { + List additionalAssignmentButtons = new ArrayList<>(); + List assignmentObjectRelations = WebComponentUtil.divideAssignmentRelationsByAllValues(loadMemberRelationsList()); + if (assignmentObjectRelations == null) { + return additionalAssignmentButtons; + } + assignmentObjectRelations.forEach(relation -> { + MultiFunctinalButtonDto buttonDto = new MultiFunctinalButtonDto(); + buttonDto.setAssignmentObjectRelation(relation); + + DisplayType additionalDispayType = WebComponentUtil.getAssignmentObjectRelationDisplayType(AbstractRoleMemberPanel.this.getPageBase(), relation, + "abstractRoleMemberPanel.menu.assignMember"); + //TODO null additinalDisplayType + CompositedIconBuilder builder = WebComponentUtil.getAssignmentRelationIconBuilder(AbstractRoleMemberPanel.this.getPageBase(), relation, + additionalDispayType.getIcon(), WebComponentUtil.createIconType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green")); + CompositedIcon icon = builder.build(); + buttonDto.setAdditionalButtonDisplayType(additionalDispayType); + buttonDto.setCompositedIcon(icon); + additionalAssignmentButtons.add(buttonDto); + }); + + return additionalAssignmentButtons; + + } + + protected TableId getTableId(QName complextType) { + return tablesId.get(complextType); + } + + protected Map getAuthorizations(QName complexType) { + return authorizations.get(complexType); + } + + protected QName getComplexTypeQName() { + return getModelObject().asPrismObject().getComplexTypeDefinition().getTypeName(); + } + + private DisplayType getCreateMemberButtonDisplayType(){ + return WebComponentUtil.createDisplayType(GuiStyleConstants.CLASS_ADD_NEW_OBJECT, "green", + AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.createMember", "", "").getString()); + } + + private DisplayType getAssignMemberButtonDisplayType(){ + return WebComponentUtil.createDisplayType(GuiStyleConstants.EVO_ASSIGNMENT_ICON, "green", + AbstractRoleMemberPanel.this.createStringResource("abstractRoleMemberPanel.menu.assignMember", "", "").getString()); + } + + protected List createRowActions() { + List menu = new ArrayList<>(); + createAssignMemberRowAction(menu); + + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_UNASSIGN)) { + menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.unassign")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + unassignMembersPerformed(target); + } + }; + + } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_UNASSIGN; + } + }); + } + + createRecomputeMemberRowAction(menu); + + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_CREATE)) { + menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.create")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + createFocusMemberPerformed(target); + } + }; + } + }); + } + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_DELETE)) { + menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.delete")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + deleteMembersPerformed(target); + } + }; + } + + }); + } + return menu; + } + + protected void createAssignMemberRowAction(List menu) { + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_ASSIGN)) { + menu.add(new InlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.assign")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + MemberOperationsHelper.assignMembers(getPageBase(), AbstractRoleMemberPanel.this.getModelObject(), target, getSupportedRelations(), null); + } + }; + } + }); + } + } + + protected void createRecomputeMemberRowAction(List menu) { + if (isAuthorized(GuiAuthorizationConstants.MEMBER_OPERATION_RECOMPUTE)) { + menu.add(new ButtonInlineMenuItem(createStringResource("abstractRoleMemberPanel.menu.recompute")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new HeaderMenuAction(AbstractRoleMemberPanel.this) { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + recomputeMembersPerformed(target); + } + }; + } + +// @Override +// public IModel getConfirmationMessageModel() { +// return getMemberTable().getSelectedObjectsCount() > 0 ? +// createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") +// : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); +// } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_RECONCILE_MENU_ITEM; + } + + }); + } + } + + + + protected abstract AvailableRelationDto getSupportedRelations(); + + protected GuiObjectListPanelConfigurationType getAdditionalPanelConfig(){ + return null; + } + + private boolean isAuthorized(String action) { + Map memeberAuthz = getAuthorizations(getComplexTypeQName()); + return WebComponentUtil.isAuthorized(memeberAuthz.get(action)); + } + + + + private List loadMemberRelationsList(){ + List assignmentTargetRelations = new ArrayList<>(); + AssignmentCandidatesSpecification spec = loadCandidateSpecification(); + assignmentTargetRelations = spec != null ? spec.getAssignmentObjectRelations() : new ArrayList<>(); + return assignmentTargetRelations; + } + + private AssignmentCandidatesSpecification loadCandidateSpecification(){ + OperationResult result = new OperationResult(OPERATION_LOAD_MEMBER_RELATIONS); + PrismObject obj = getModelObject().asPrismObject(); + AssignmentCandidatesSpecification spec = null; + try { + spec = getPageBase().getModelInteractionService() + .determineAssignmentHolderSpecification(obj, result); + } catch (SchemaException | ConfigurationException ex){ + result.recordPartialError(ex.getLocalizedMessage()); + LOGGER.error("Couldn't load member relations list for the object {} , {}", obj.getName(), ex.getLocalizedMessage()); + } + return spec; + } + + protected void assignMembers(AjaxRequestTarget target, AvailableRelationDto availableRelationList, + List objectTypes, List archetypeRefList, boolean isOrgTreePanelVisible) { + MemberOperationsHelper.assignMembers(getPageBase(), getModelObject(), target, availableRelationList, + objectTypes, archetypeRefList, isOrgTreePanelVisible); + } + + private void unassignMembersPerformed(AjaxRequestTarget target) { + QueryScope scope = getQueryScope(false); + + ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), + createStringResource("abstractRoleMemberPanel.unassignAllMembersConfirmationLabel")) { + private static final long serialVersionUID = 1L; + + @Override + protected List getSupportedObjectTypes() { + return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); + } + + @Override + protected List getSupportedRelations() { + return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); + } + + @Override + protected boolean isFocusTypeSelectorVisible() { + return !QueryScope.SELECTED.equals(scope); + } + + + protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { + unassignMembersPerformed(type, scope, relations, target); + } + + @Override + protected QName getDefaultObjectType() { + return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), + AbstractRoleMemberPanel.this.getDefaultObjectType()); + } + }; + + getPageBase().showMainPopup(chooseTypePopupContent, target); + } + + private void deleteMembersPerformed(AjaxRequestTarget target) { + QueryScope scope = getQueryScope(false); + ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel(getPageBase().getMainPopupBodyId(), + createStringResource("abstractRoleMemberPanel.deleteAllMembersConfirmationLabel")) { + private static final long serialVersionUID = 1L; + + @Override + protected List getSupportedObjectTypes() { + return AbstractRoleMemberPanel.this.getSupportedObjectTypes(true); + } + + @Override + protected List getSupportedRelations() { + return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); + } + + protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { + deleteMembersPerformed(type, scope, relations, target); + + } + + @Override + protected boolean isFocusTypeSelectorVisible() { + return !QueryScope.SELECTED.equals(scope); + } + + @Override + protected QName getDefaultObjectType() { + return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), + AbstractRoleMemberPanel.this.getDefaultObjectType()); + } + + }; + + getPageBase().showMainPopup(chooseTypePopupContent, target); + + } + + protected void createFocusMemberPerformed(AjaxRequestTarget target) { + createFocusMemberPerformed(target, null); + } + + protected void createFocusMemberPerformed(AjaxRequestTarget target, AssignmentObjectRelation relationSpec) { + if (relationSpec != null){ + try { + List newReferences = new ArrayList<>(); + if (CollectionUtils.isEmpty(relationSpec.getRelations())){ + relationSpec.setRelations(Arrays.asList(RelationTypes.MEMBER.getRelation())); + } + ObjectReferenceType memberRef = ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relationSpec.getRelations().get(0)); + newReferences.add(memberRef); + if (CollectionUtils.isNotEmpty(relationSpec.getArchetypeRefs())) { + newReferences.add(relationSpec.getArchetypeRefs().get(0)); + } + QName newMemberType = CollectionUtils.isNotEmpty(relationSpec.getObjectTypes()) ? relationSpec.getObjectTypes().get(0) : + getSupportedObjectTypes(false).get(0); + WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), newMemberType, newReferences); + } catch (SchemaException e) { + throw new SystemException(e.getMessage(), e); + } + } else { + ChooseFocusTypeAndRelationDialogPanel chooseTypePopupContent = new ChooseFocusTypeAndRelationDialogPanel( + getPageBase().getMainPopupBodyId()) { + private static final long serialVersionUID = 1L; + + @Override + protected List getSupportedObjectTypes() { + return AbstractRoleMemberPanel.this.getNewMemberObjectTypes(); + } + + @Override + protected List getSupportedRelations() { + return AbstractRoleMemberPanel.this.getSupportedRelations().getAvailableRelationList(); + } + + protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { + if (type == null) { + getSession().warn("No type was selected. Cannot create member"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + if (relations == null || relations.isEmpty()) { + getSession().warn("No relation was selected. Cannot create member"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + AbstractRoleMemberPanel.this.getPageBase().hideMainPopup(target); + try { + List newReferences = new ArrayList<>(); + for (QName relation : relations) { + newReferences.add(ObjectTypeUtil.createObjectRef(AbstractRoleMemberPanel.this.getModelObject(), relation)); + } + WebComponentUtil.initNewObjectWithReference(AbstractRoleMemberPanel.this.getPageBase(), type, newReferences); + } catch (SchemaException e) { + throw new SystemException(e.getMessage(), e); + } + + } + + @Override + protected QName getDefaultObjectType() { + if (relationSpec != null && CollectionUtils.isNotEmpty(relationSpec.getObjectTypes())) { + return relationSpec.getObjectTypes().get(0); + } + return super.getDefaultObjectType(); + } + + @Override + protected boolean isFocusTypeSelectorVisible() { + return relationSpec == null; + } + }; + + getPageBase().showMainPopup(chooseTypePopupContent, target); + } + } + + protected void deleteMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { + if (relations == null || relations.isEmpty()) { + getSession().warn("No relation was selected. Cannot perform delete members"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + MemberOperationsHelper.deleteMembersPerformed(getPageBase(), scope, getActionQuery(scope, relations), type, target); + } + + protected void unassignMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { + if (relations == null || relations.isEmpty()) { + getSession().warn("No relation was selected. Cannot perform unassign members"); + target.add(this); + target.add(getPageBase().getFeedbackPanel()); + return; + } + MemberOperationsHelper.unassignMembersPerformed(getPageBase(), getModelObject(), scope, getActionQuery(scope, relations), relations, type, target); + } + + private ObjectViewDto getParameter(String panelId) { + ChooseTypePanel tenantChoice = (ChooseTypePanel) get(createComponentPath(ID_FORM, panelId)); + return tenantChoice.getModelObject(); + } + + protected ObjectQuery getActionQuery(QueryScope scope, Collection relations) { + switch (scope) { + case ALL: + return createAllMemberQuery(relations); + case ALL_DIRECT: + return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); + case SELECTED: + return MemberOperationsHelper.createSelectedObjectsQuery(getMemberTable().getSelectedObjects(), getPrismContext()); + } + + return null; + } + + protected void initSearch(Form form) { + + List scopeValues = Arrays.asList(SearchBoxScopeType.values()); + DropDownFormGroup searchScrope = createDropDown(ID_SEARCH_SCOPE, + Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getOrgSearchScope() : scopeDefaultValue), + scopeValues, + WebComponentUtil.getEnumChoiceRenderer(AbstractRoleMemberPanel.this), + "abstractRoleMemberPanel.searchScope", "abstractRoleMemberPanel.searchScope.tooltip", true); + searchScrope.add(new VisibleBehaviour(() -> getModelObject() instanceof OrgType)); + form.add(searchScrope); + + List supportedTypes = getSupportedObjectTypes(false); + DropDownFormGroup typeSelect = createDropDown(ID_OBJECT_TYPE, + Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : WebComponentUtil.classToQName(getPrismContext(), getDefaultObjectType())), + supportedTypes, new QNameObjectTypeChoiceRenderer(){ + private static final long serialVersionUID = 1L; + + @Override + public Object getDisplayValue(QName qname) { + if (qname == null || getObjectTypesListParentType().equals(qname)){ + return StringUtils.leftPad(createStringResource("ObjectTypes.all").getString(), 1); + } else { + return super.getDisplayValue(qname); + } + } + + @Override + public QName getObject(String id, IModel> choices) { + QName qname = super.getObject(id, choices); + if (qname == null){ + return getObjectTypesListParentType(); + } + return qname; + } + + }, + "abstractRoleMemberPanel.type", "abstractRoleMemberPanel.type.tooltip", false); + form.add(typeSelect); + + RelationDropDownChoicePanel relationSelector = new RelationDropDownChoicePanel(ID_SEARCH_BY_RELATION, + getMemberPanelStorage() != null ? getMemberPanelStorage().getRelation() : getSupportedRelations().getDefaultRelation(), + getSupportedRelations().getAvailableRelationList(), true){ + private static final long serialVersionUID = 1L; + + @Override + protected void onValueChanged(AjaxRequestTarget target){ + refreshAll(target); + } + + @Override + protected String getNullValidDisplayValue(){ + return getString("RelationTypes.ANY"); + } + }; + form.add(relationSelector); + + ChooseTypePanel tenant = createParameterPanel(ID_TENANT, true); + form.add(tenant); + tenant.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); + + ChooseTypePanel project = createParameterPanel(ID_PROJECT, false); + form.add(project); + project.add(new VisibleBehaviour(() -> getModelObject() instanceof RoleType)); + + CheckFormGroup includeIndirectMembers = new CheckFormGroup(ID_INDIRECT_MEMBERS, + Model.of(getMemberPanelStorage() != null ? getMemberPanelStorage().getIndirect() : false), + createStringResource("abstractRoleMemberPanel.indirectMembers"), "abstractRoleMemberPanel.indirectMembers.tooltip", false, "col-md-4", "col-md-2"); + includeIndirectMembers.getCheck().add(new AjaxFormComponentUpdatingBehavior("change") { + + private static final long serialVersionUID = 1L; + + protected void onUpdate(AjaxRequestTarget target) { + refreshAll(target); + }; + + }); + + includeIndirectMembers.getCheck().add(new EnableBehaviour(() -> + getSearchScopeValue().equals(SearchBoxScopeType.ONE_LEVEL) || !searchScrope.isVisible())); + includeIndirectMembers.setOutputMarkupId(true); + form.add(includeIndirectMembers); + + } + + protected List getSupportedObjectTypes(boolean includeAbstractTypes) { + return WebComponentUtil.createFocusTypeList(includeAbstractTypes); + } + + protected QName getObjectTypesListParentType(){ + return FocusType.COMPLEX_TYPE; + } + + protected List getNewMemberObjectTypes() { + return WebComponentUtil.createFocusTypeList(); + } + + private ChooseTypePanel createParameterPanel(String id, boolean isTenant) { + + ChooseTypePanel orgSelector = new ChooseTypePanel(id, Model.of(new ObjectViewDto())) { + + private static final long serialVersionUID = 1L; + + @Override + protected void executeCustomAction(AjaxRequestTarget target, OrgType object) { + refreshAll(target); + } + + @Override + protected void executeCustomRemoveAction(AjaxRequestTarget target) { + refreshAll(target); + } + + @Override + protected ObjectQuery getChooseQuery() { + S_FilterEntryOrEmpty q = getPrismContext().queryFor(OrgType.class); + if (isTenant) { + return q.item(OrgType.F_TENANT).eq(true).build(); + } else { + return q.not().item(OrgType.F_TENANT).eq(true).build(); + } + } + + @Override + protected boolean isSearchEnabled() { + return true; + } + + @Override + public Class getObjectTypeClass() { + return OrgType.class; + } + + @Override + protected AttributeAppender getInputStyleClass(){ + return AttributeAppender.append("class", "col-md-10"); + } + + }; + orgSelector.setOutputMarkupId(true); + orgSelector.setOutputMarkupPlaceholderTag(true); + return orgSelector; + + } + + private DropDownFormGroup createDropDown(String id, IModel defaultModel, final List values, + IChoiceRenderer renderer, String labelKey, String tooltipKey, boolean required) { + DropDownFormGroup listSelect = new DropDownFormGroup(id, defaultModel, Model.ofList(values), renderer, createStringResource(labelKey), + tooltipKey, false, "col-md-4", "col-md-8", required){ + private static final long serialVersionUID = 1L; + + @Override + protected String getNullValidDisplayValue(){ + return getString("ObjectTypes.all"); + } + }; + + listSelect.getInput().add(new OnChangeAjaxBehavior() { + private static final long serialVersionUID = 1L; + + @Override + protected void onUpdate(AjaxRequestTarget target) { + refreshAll(target); + } + }); + listSelect.setOutputMarkupId(true); + return listSelect; + } + + protected void refreshAll(AjaxRequestTarget target) { + updateMembersPanelSessionStorage(); + + DropDownFormGroup typeChoice = (DropDownFormGroup) get(createComponentPath(ID_FORM, ID_OBJECT_TYPE)); + QName type = getMemberPanelStorage() != null ? getMemberPanelStorage().getType().getTypeQName() : typeChoice.getModelObject(); + getMemberTable().clearCache(); + getMemberTable().refreshTable(WebComponentUtil.qnameToClass(getPrismContext(), type, FocusType.class), target); + target.add(this); + } + + + private MainObjectListPanel getMemberTable() { + return (MainObjectListPanel) get(createComponentPath(ID_FORM, ID_CONTAINER_MEMBER, ID_MEMBER_TABLE)); + } + + protected QueryScope getQueryScope(boolean isRecompute) { + if (CollectionUtils.isNotEmpty(MemberOperationsHelper.getFocusOidToRecompute(getMemberTable().getSelectedObjects()))) { + return QueryScope.SELECTED; + } + + if (getIndirectmembersPanel().getValue()) { + return QueryScope.ALL; + } + + return QueryScope.ALL_DIRECT; + } + + private CheckFormGroup getIndirectmembersPanel() { + return (CheckFormGroup) get(createComponentPath(ID_FORM, ID_INDIRECT_MEMBERS)); + } + + protected void recomputeMembersPerformed(AjaxRequestTarget target) { + + StringResourceModel confirmModel = getMemberTable().getSelectedObjectsCount() > 0 ? + createStringResource("abstractRoleMemberPanel.recomputeSelectedMembersConfirmationLabel") + : createStringResource("abstractRoleMemberPanel.recomputeAllMembersConfirmationLabel"); + + ConfigureTaskConfirmationPanel dialog = new ConfigureTaskConfirmationPanel(((PageBase)getPage()).getMainPopupBodyId(), + confirmModel) { + + private static final long serialVersionUID = 1L; + + @Override + protected PrismObject getTask(AjaxRequestTarget target) { + Task task = MemberOperationsHelper.createRecomputeMembersTask(getPageBase(), getQueryScope(true), + getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); + if (task == null) { + return null; + } + PrismObject recomputeTask = task.getClonedTaskObject(); + TaskType recomputeTaskType = recomputeTask.asObjectable(); + recomputeTaskType.getAssignment().add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value(), ObjectTypes.ARCHETYPE, getPrismContext())); + return recomputeTask; + } + + @Override + public StringResourceModel getTitle() { + return createStringResource("pageUsers.message.confirmActionPopupTitle"); + } + + @Override + public void yesPerformed(AjaxRequestTarget target) { + MemberOperationsHelper.recomputeMembersPerformed(getPageBase(), getQueryScope(true), + getActionQuery(getQueryScope(true), getSupportedRelations().getAvailableRelationList()), target); + } + }; + ((PageBase)getPage()).showMainPopup(dialog, target); + } + + protected ObjectQuery createContentQuery() { + CheckFormGroup isIndirect = getIndirectmembersPanel(); + List relations = QNameUtil.match(getSelectedRelation(), PrismConstants.Q_ANY) ? getSupportedRelations().getAvailableRelationList() : Arrays.asList(getSelectedRelation()); + return createMemberQuery(isIndirect != null ? isIndirect.getValue() : false, relations); + + } + + protected QName getSelectedRelation(){ + MemberPanelStorage storage = getMemberPanelStorage(); + if (storage != null){ + return storage.getRelation(); + } + RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); + return relationDropDown.getRelationValue(); + } + + private SearchBoxScopeType getSearchScopeValue(){ + if (getMemberPanelStorage() != null){ + return getMemberPanelStorage().getOrgSearchScope(); + } + DropDownFormGroup searchScopeComponent = (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); + return searchScopeComponent.getModelObject(); + } + + protected ObjectTypes getSearchType() { + DropDownFormGroup searchByTypeChoice = (DropDownFormGroup) get( + createComponentPath(ID_FORM, ID_OBJECT_TYPE)); + QName typeName = searchByTypeChoice.getModelObject(); + return ObjectTypes.getObjectTypeFromTypeQName(typeName); + } + + protected ObjectQuery createMemberQuery(boolean indirect, Collection relations) { + if (indirect) { + return createAllMemberQuery(relations); + } + + return MemberOperationsHelper.createDirectMemberQuery(getModelObject(), getSearchType().getTypeQName(), relations, getParameter(ID_TENANT), getParameter(ID_PROJECT), getPrismContext()); + } + + + protected ObjectQuery createAllMemberQuery(Collection relations) { + return getPrismContext().queryFor(FocusType.class) + .item(FocusType.F_ROLE_MEMBERSHIP_REF).ref(MemberOperationsHelper.createReferenceValuesList(getModelObject(), relations)) + .build(); + } + + + protected ObjectReferenceType createReference() { + ObjectReferenceType ref = ObjectTypeUtil.createObjectRef(getModelObject(), getPageBase().getPrismContext()); + return ref; + } + + protected void detailsPerformed(AjaxRequestTarget target, ObjectType object) { + if (WebComponentUtil.hasDetailsPage(object.getClass())) { + WebComponentUtil.dispatchToObjectDetailsPage(object.getClass(), object.getOid(), this, true); + } else { + error("Could not find proper response page"); + throw new RestartResponseException(getPageBase()); + } + } + + protected List, String>> createMembersColumns() { + List, String>> columns = new ArrayList<>(); + + IColumn, String> column = new AbstractExportableColumn, String>( + createStringResource("TreeTablePanel.fullName.displayName")) { + private static final long serialVersionUID = 1L; + + @Override + public void populateItem(Item>> cellItem, + String componentId, IModel> rowModel) { + SelectableBean bean = rowModel.getObject(); + ObjectType object = bean.getValue(); + cellItem.add(new Label(componentId, + getMemberObjectDisplayName(object, true))); + } + + @Override + public IModel getDataModel(IModel> rowModel) { + return Model.of(getMemberObjectDisplayName(rowModel.getObject().getValue(), true)); + } + + }; + columns.add(column); + + column = new AbstractExportableColumn, String>( + createStringResource("TreeTablePanel.identifier.description")) { + private static final long serialVersionUID = 1L; + + @Override + public void populateItem(Item>> cellItem, + String componentId, IModel> rowModel) { + SelectableBean bean = rowModel.getObject(); + ObjectType object = bean.getValue(); + cellItem.add(new Label(componentId, getMemberObjectIdentifier(object))); + } + + @Override + public IModel getDataModel(IModel> rowModel) { + return Model.of(getMemberObjectIdentifier(rowModel.getObject().getValue())); + } + + }; + columns.add(column); +// if (isRelationColumnVisible()){ + columns.add(createRelationColumn()); +// } + return columns; + } + + protected IColumn, String> createRelationColumn() { + return new AbstractExportableColumn, String>( + createStringResource("roleMemberPanel.relation")) { + private static final long serialVersionUID = 1L; + + @Override + public void populateItem(Item>> cellItem, + String componentId, IModel> rowModel) { + cellItem.add(new Label(componentId, + getRelationValue(rowModel.getObject().getValue()))); + } + + @Override + public IModel getDataModel(IModel> rowModel) { + return Model.of(getRelationValue(rowModel.getObject().getValue())); + } + + }; + } + + protected boolean isRelationColumnVisible(){ + return false; + } + + + private String getMemberObjectDisplayName(ObjectType object){ + return getMemberObjectDisplayName(object, false); + } + + private String getMemberObjectDisplayName(ObjectType object, boolean translate){ + if (object == null){ + return ""; + } + if (object instanceof UserType) { + return WebComponentUtil.getTranslatedPolyString(((UserType) object).getFullName()); + } else if (object instanceof AbstractRoleType) { + return WebComponentUtil.getTranslatedPolyString(((AbstractRoleType) object).getDisplayName()); + } else { + return ""; + } + } + + private String getMemberObjectIdentifier(ObjectType object){ + if (object == null){ + return ""; + } + if (object instanceof UserType) { + return ((UserType) object).getEmailAddress(); + } else if (object instanceof AbstractRoleType) { + return ((AbstractRoleType) object).getIdentifier(); + } else { + return object.getDescription(); + } + } + + private Collection> getSearchOptions(){ + return SelectorOptions + .createCollection(GetOperationOptions.createDistinct()); + } + + protected Class getDefaultObjectType(){ + return (Class) FocusType.class; + } + + protected Form getFormComponent(){ + return (Form) get(ID_FORM); + } + + + private String getRelationValue(ObjectType focusObject){ + String relation = ""; + if (FocusType.class.isAssignableFrom(focusObject.getClass())) { + // Do NOT take relation from an assignment. Use roleMembershipRef instead. Reasons: + // 1. Authorizations (MID-4893). User may be authorized just for roleMemberhsipRef and not for assignment + // Authorization for roleMembershipRef is enough to display member panel. + // 2. There may be assignments that are not valid. We do not want to display relation for those. + for (ObjectReferenceType roleMembershipRef : getMembershipReferenceList((FocusType) focusObject)) { + relation = buildRelation(roleMembershipRef, relation); + } + + } + return relation; + + } + + protected List getMembershipReferenceList(FocusType focusObject){ + return focusObject.getRoleMembershipRef(); + } + + private String buildRelation(ObjectReferenceType roleMembershipRef, String relation) { + if (roleMembershipRef.getOid().equals(getModelObject().getOid())) { + QName assignmentRelation = roleMembershipRef.getRelation(); + if (getSupportedRelations().getAvailableRelationList().stream().anyMatch(r -> QNameUtil.match(r, assignmentRelation))) { + if (!StringUtils.isBlank(relation)) { + relation += ","; + } + relation += assignmentRelation.getLocalPart(); + } + } + return relation; + } + + protected void updateMembersPanelSessionStorage(){ + MemberPanelStorage storage = getMemberPanelStorage(); + if (storage != null){ + storage.setType(getSearchType()); + + RelationDropDownChoicePanel relationDropDown = (RelationDropDownChoicePanel) get(createComponentPath(ID_FORM, ID_SEARCH_BY_RELATION)); + storage.setRelation(relationDropDown.getRelationValue()); + + CheckFormGroup indirectPanel = getIndirectmembersPanel(); + if (indirectPanel != null){ + storage.setIndirect(indirectPanel.getValue()); + } + + DropDownFormGroup searchScopeComponent = + (DropDownFormGroup)get(createComponentPath(ID_FORM, ID_SEARCH_SCOPE)); + storage.setOrgSearchScope(searchScopeComponent.getModelObject()); + } + } + + protected MemberPanelStorage getMemberPanelStorage(){ + return null; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java index 89e618dfdbf..5a4219e3f69 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java @@ -143,7 +143,18 @@ public static void recomputeMembersPerformed(PageBa public static Task createRecomputeMembersTask(PageBase pageBase, QueryScope scope, ObjectQuery query, AjaxRequestTarget target) { - return createRecomputeOrDeleteMembersTask(pageBase, scope, query, target, "recompute", RECOMPUTE_OPERATION); + Task operationalTask = pageBase.createSimpleTask(getTaskName(RECOMPUTE_OPERATION, scope)); + OperationResult parentResult = operationalTask.getResult(); + try { + return WebComponentUtil.createRecomputeMemberOperationTask(operationalTask, AssignmentHolderType.COMPLEX_TYPE, query, + null, parentResult, pageBase); + } catch (SchemaException e) { + parentResult.recordFatalError(parentResult.getOperation(), e); + LoggingUtils.logUnexpectedException(LOGGER, + "Failed to execute operation " + parentResult.getOperation(), e); + target.add(pageBase.getFeedbackPanel()); + } + return null; } private static Task createRecomputeOrDeleteMembersTask(PageBase pageBase, QueryScope scope, diff --git a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java index cec7ccbe9f2..02c4e1a4de8 100644 --- a/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java +++ b/model/model-api/src/main/java/com/evolveum/midpoint/model/api/ModelPublicConstants.java @@ -1,45 +1,46 @@ -/* - * Copyright (c) 2010-2015 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.model.api; - -import com.evolveum.midpoint.schema.constants.SchemaConstants; - -/** - * Model constants referenced from the outside. - * (TODO reconsider with regards to SchemaConstants) - * - * @author mederly - */ -public class ModelPublicConstants { - - private static final String NS_SYNCHRONIZATION_PREFIX = SchemaConstants.NS_MODEL +"/synchronization"; - public static final String NS_SYNCHRONIZATION_TASK_PREFIX = NS_SYNCHRONIZATION_PREFIX + "/task"; - - public static final String DELETE_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete/handler-3"; // TODO why "synchronization"? - public static final String REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/reindex/handler-3"; - public static final String AUDIT_REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/auditReindex/handler-3"; - public static final String CLEANUP_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/cleanup/handler-3"; - public static final String SHADOW_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadow-integrity-check/handler-3"; - public static final String OBJECT_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/object-integrity-check/handler-3"; - public static final String DEPRECATED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/focus-validation-scanner/handler-3"; - public static final String FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/focus-validity-scanner/handler-3"; - public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/partitioned-focus-validity-scanner/handler-3"; - public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_1 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#1"; - public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_2 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#2"; - public static final String TRIGGER_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/trigger/scanner/handler-3"; - public static final String SHADOW_REFRESH_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadowRefresh/handler-3"; - public static final String RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/reconciliation/handler-3"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/partitioned-reconciliation/handler-3"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_1 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#1"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_2 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#2"; - public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_3 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#3"; - public static final String SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/scripting/handler-3"; - public static final String ITERATIVE_SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/iterative-scripting/handler-3"; - public static final String EXECUTE_DELTAS_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/execute-deltas/handler-3"; - public static final String EXECUTE_CHANGES_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/execute/handler-3"; - public static final String DELETE_NOT_UPDATE_SHADOW_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete-not-updated-shadow/handler-3"; -} +/* + * Copyright (c) 2010-2015 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.model.api; + +import com.evolveum.midpoint.schema.constants.SchemaConstants; + +/** + * Model constants referenced from the outside. + * (TODO reconsider with regards to SchemaConstants) + * + * @author mederly + */ +public class ModelPublicConstants { + + private static final String NS_SYNCHRONIZATION_PREFIX = SchemaConstants.NS_MODEL +"/synchronization"; + public static final String NS_SYNCHRONIZATION_TASK_PREFIX = NS_SYNCHRONIZATION_PREFIX + "/task"; + + public static final String DELETE_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete/handler-3"; // TODO why "synchronization"? + public static final String REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/reindex/handler-3"; + public static final String AUDIT_REINDEX_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/auditReindex/handler-3"; + public static final String CLEANUP_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/cleanup/handler-3"; + public static final String SHADOW_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadow-integrity-check/handler-3"; + public static final String OBJECT_INTEGRITY_CHECK_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/object-integrity-check/handler-3"; + public static final String DEPRECATED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/focus-validation-scanner/handler-3"; + public static final String FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/focus-validity-scanner/handler-3"; + public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/partitioned-focus-validity-scanner/handler-3"; + public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_1 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#1"; + public static final String PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI_2 = PARTITIONED_FOCUS_VALIDITY_SCANNER_TASK_HANDLER_URI + "#2"; + public static final String TRIGGER_SCANNER_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/trigger/scanner/handler-3"; + public static final String SHADOW_REFRESH_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/shadowRefresh/handler-3"; + public static final String RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/reconciliation/handler-3"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/partitioned-reconciliation/handler-3"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_1 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#1"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_2 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#2"; + public static final String PARTITIONED_RECONCILIATION_TASK_HANDLER_URI_3 = PARTITIONED_RECONCILIATION_TASK_HANDLER_URI + "#3"; + public static final String SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/scripting/handler-3"; + public static final String ITERATIVE_SCRIPT_EXECUTION_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/iterative-scripting/handler-3"; + public static final String EXECUTE_DELTAS_TASK_HANDLER_URI = SchemaConstants.NS_MODEL + "/execute-deltas/handler-3"; + public static final String EXECUTE_CHANGES_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/execute/handler-3"; + public static final String DELETE_NOT_UPDATE_SHADOW_TASK_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/delete-not-updated-shadow/handler-3"; + public static final String RECOMPUTE_HANDLER_URI = NS_SYNCHRONIZATION_TASK_PREFIX + "/recompute/handler-3"; +} From 4ece39bf1f93d4e99f0ab025bac7bc284d150f5e Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Sun, 8 Mar 2020 22:50:48 +0100 Subject: [PATCH 26/55] another improvements for task page, including - liveSync token editor (MID-6004), - download button for generated report for report task - change iterative bulk -> recompute member task - adding archetype for generated recompute member task (MID-5959) and some refactoring + cleanup --- .../gui/api/util/WebComponentUtil.java | 42 ++ .../web/page/admin/reports/PageReports.java | 482 +++++++++--------- .../admin/resources/ResourceContentPanel.java | 2 +- .../admin/roles/MemberOperationsHelper.java | 2 + .../server/LivesyncTokenEditorPanel.html | 35 ++ .../server/LivesyncTokenEditorPanel.java | 173 +++++++ .../web/page/admin/server/PageTask.java | 226 ++++++-- .../page/admin/server/TaskTabsVisibility.java | 42 +- .../xml/ns/public/common/common-core-3.xsd | 9 +- 9 files changed, 702 insertions(+), 311 deletions(-) create mode 100644 gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.html create mode 100644 gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.java diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java index f5384a7f08d..5ceeb8173fa 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/util/WebComponentUtil.java @@ -689,6 +689,48 @@ public static boolean isWorkflowTask(TaskType task) { return task != null && TaskCategory.WORKFLOW.equals(task.getCategory()); } + public static boolean isReconciliation(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_RECONCILIATION_TASK); + } + + public static boolean isRecomputation(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK); + } + + public static boolean isReport(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_REPORT_TASK); + } + + public static boolean isImport(TaskType task){ + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_IMPORT_TASK); + } + + public static boolean isLiveSync(TaskType task) { + return isArchetypedTask(task, SystemObjectsType.ARCHETYPE_LIVE_SYNC_TASK); + } + + private static boolean isArchetypedTask(TaskType taskType, SystemObjectsType archetype) { + ObjectReferenceType archetypeRef = getArchetypeReference(taskType); + if (archetypeRef == null){ + return false; + } + return archetype.value().equals(archetypeRef.getOid()); + } + + private static ObjectReferenceType getArchetypeReference(TaskType task) { + ObjectReferenceType archetypeRef = null; + if (task.getAssignment() == null || task.getAssignment().size() == 0) { + return archetypeRef; + } + for (AssignmentType assignment : task.getAssignment()) { + if (StringUtils.isNotEmpty(assignment.getTargetRef().getOid()) + && assignment.getTargetRef() != null && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { + archetypeRef = assignment.getTargetRef(); + } + } + return archetypeRef; + } + public static void iterativeExecuteBulkAction(PageBase pageBase, ExecuteScriptType script, Task task, OperationResult result ) throws SchemaException, SecurityViolationException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException{ diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java index 8677a761273..5023f565810 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java @@ -1,237 +1,245 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.web.page.admin.reports; - -import com.evolveum.midpoint.gui.api.GuiStyleConstants; -import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; -import com.evolveum.midpoint.model.api.AssignmentObjectRelation; -import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; -import com.evolveum.midpoint.prism.PrismContainer; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.security.api.AuthorizationConstants; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.application.AuthorizationAction; -import com.evolveum.midpoint.web.application.PageDescriptor; -import com.evolveum.midpoint.web.application.Url; -import com.evolveum.midpoint.web.component.data.Table; -import com.evolveum.midpoint.web.component.data.column.ColumnMenuAction; -import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; -import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; -import com.evolveum.midpoint.web.component.util.SelectableBean; -import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; -import com.evolveum.midpoint.web.page.admin.PageAdmin; -import com.evolveum.midpoint.web.page.admin.configuration.PageAdminConfiguration; -import com.evolveum.midpoint.web.page.admin.reports.component.RunReportPopupPanel; -import com.evolveum.midpoint.web.session.UserProfileStorage; -import com.evolveum.midpoint.web.util.OnePageParameterEncoder; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportEngineSelectionType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportParameterType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType; - -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; -import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; -import org.apache.wicket.markup.html.form.Form; -import org.apache.wicket.request.mapper.parameter.PageParameters; - -import java.util.ArrayList; -import java.util.List; - - -/** - * @author lazyman - */ -@PageDescriptor( - urls = { - @Url(mountUrl = "/admin/reports", matchUrlForSecurity = "/admin/reports") - }, - action = { - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_ALL_URL, - label = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_LABEL, - description = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_DESCRIPTION), - @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_URL, - label = "PageReports.auth.reports.label", - description = "PageReports.auth.reports.description")}) -public class PageReports extends PageAdmin { - - private static final Trace LOGGER = TraceManager.getTrace(PageReports.class); - - private static final String DOT_CLASS = PageReports.class.getName() + "."; - private static final String OPERATION_RUN_REPORT = DOT_CLASS + "runReport"; - - private static final String ID_MAIN_FORM = "mainForm"; - private static final String ID_REPORTS_TABLE = "reportsTable"; - - public PageReports() { - initLayout(); - } - - private void initLayout() { - Form mainForm = new com.evolveum.midpoint.web.component.form.Form(ID_MAIN_FORM); - add(mainForm); - - MainObjectListPanel table = - new MainObjectListPanel(ID_REPORTS_TABLE, ReportType.class, UserProfileStorage.TableId.PAGE_REPORTS, - null) { - - @Override - protected IColumn, String> createCheckboxColumn() { - return null; - } - - @Override - public void objectDetailsPerformed(AjaxRequestTarget target, ReportType report) { - if (report != null) { - PageReports.this.reportDetailsPerformed(target, report.getOid()); - } - } - - @Override - protected List, String>> createColumns() { - return PageReports.this.initColumns(); - } - - @Override - protected List createInlineMenu() { - return PageReports.this.createInlineMenu(); - } - - @Override - protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { - navigateToNext(PageNewReport.class); - } - }; - table.setOutputMarkupId(true); - mainForm.add(table); - - } - - private List, String>> initColumns() { - List, String>> columns = new ArrayList<>(); - - IColumn column = new PropertyColumn(createStringResource("PageReports.table.description"), "value.description"); - columns.add(column); - - return columns; - } - - private void reportDetailsPerformed(AjaxRequestTarget target, String oid) { - PageParameters params = new PageParameters(); - params.add(OnePageParameterEncoder.PARAMETER, oid); - navigateToNext(PageCreatedReports.class, params); - } - - private List createInlineMenu(){ - List menu = new ArrayList<>(); - menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.run")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new ColumnMenuAction>() { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - ReportType report = getRowModel().getObject().getValue(); - runReportPerformed(target, report); - } - }; - } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_START_MENU_ITEM; - } - - @Override - public boolean isHeaderMenuItem(){ - return false; - } - }); - menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.configure")) { - private static final long serialVersionUID = 1L; - - @Override - public InlineMenuItemAction initAction() { - return new ColumnMenuAction>() { - private static final long serialVersionUID = 1L; - - @Override - public void onClick(AjaxRequestTarget target) { - ReportType reportObject = getRowModel().getObject().getValue(); - configurePerformed(target, reportObject); - } - }; - } - - @Override - public String getButtonIconCssClass() { - return GuiStyleConstants.CLASS_EDIT_MENU_ITEM; - } - - @Override - public boolean isHeaderMenuItem(){ - return false; - } - }); - return menu; - - } - - private void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { - OperationResult result = new OperationResult(OPERATION_RUN_REPORT); - Task task = createSimpleTask(OPERATION_RUN_REPORT); - try { - getReportManager().runReport(reportType.asPrismObject(), reportParam, task, result); - } catch (Exception ex) { - result.recordFatalError(ex); - } finally { - result.computeStatusIfUnknown(); - } - - showResult(result); - target.add(getFeedbackPanel(), get(createComponentPath(ID_MAIN_FORM))); - hideMainPopup(target); - - } - - protected void runReportPerformed(AjaxRequestTarget target, ReportType report) { - - if(report.getReportEngine() != null && report.getReportEngine().equals(ReportEngineSelectionType.DASHBOARD)) { - runConfirmPerformed(target, report, null); - return; - } - - RunReportPopupPanel runReportPopupPanel = new RunReportPopupPanel(getMainPopupBodyId(), report) { - - private static final long serialVersionUID = 1L; - - protected void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { - PageReports.this.runConfirmPerformed(target, reportType, reportParam); - hideMainPopup(target); - - }; - }; - showMainPopup(runReportPopupPanel, target); - - } - - private void configurePerformed(AjaxRequestTarget target, ReportType report) { - PageParameters params = new PageParameters(); - params.add(OnePageParameterEncoder.PARAMETER, report.getOid()); - navigateToNext(PageReport.class, params); - } - - private Table getReportTable() { - return (Table) get(createComponentPath(ID_MAIN_FORM, ID_REPORTS_TABLE)); - } -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.web.page.admin.reports; + +import com.evolveum.midpoint.gui.api.GuiStyleConstants; +import com.evolveum.midpoint.gui.api.component.MainObjectListPanel; +import com.evolveum.midpoint.model.api.AssignmentObjectRelation; +import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; +import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.schema.constants.ObjectTypes; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.security.api.AuthorizationConstants; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.application.AuthorizationAction; +import com.evolveum.midpoint.web.application.PageDescriptor; +import com.evolveum.midpoint.web.application.Url; +import com.evolveum.midpoint.web.component.data.Table; +import com.evolveum.midpoint.web.component.data.column.ColumnMenuAction; +import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItem; +import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; +import com.evolveum.midpoint.web.component.util.SelectableBean; +import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; +import com.evolveum.midpoint.web.page.admin.PageAdmin; +import com.evolveum.midpoint.web.page.admin.configuration.PageAdminConfiguration; +import com.evolveum.midpoint.web.page.admin.reports.component.RunReportPopupPanel; +import com.evolveum.midpoint.web.session.UserProfileStorage; +import com.evolveum.midpoint.web.util.OnePageParameterEncoder; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportEngineSelectionType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportParameterType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ReportType; + +import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; + +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; +import org.apache.wicket.extensions.markup.html.repeater.data.table.PropertyColumn; +import org.apache.wicket.markup.html.form.Form; +import org.apache.wicket.request.mapper.parameter.PageParameters; + +import java.util.ArrayList; +import java.util.List; + + +/** + * @author lazyman + */ +@PageDescriptor( + urls = { + @Url(mountUrl = "/admin/reports", matchUrlForSecurity = "/admin/reports") + }, + action = { + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_ALL_URL, + label = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_LABEL, + description = PageAdminConfiguration.AUTH_CONFIGURATION_ALL_DESCRIPTION), + @AuthorizationAction(actionUri = AuthorizationConstants.AUTZ_UI_REPORTS_URL, + label = "PageReports.auth.reports.label", + description = "PageReports.auth.reports.description")}) +public class PageReports extends PageAdmin { + + private static final Trace LOGGER = TraceManager.getTrace(PageReports.class); + + private static final String DOT_CLASS = PageReports.class.getName() + "."; + private static final String OPERATION_RUN_REPORT = DOT_CLASS + "runReport"; + + private static final String ID_MAIN_FORM = "mainForm"; + private static final String ID_REPORTS_TABLE = "reportsTable"; + + public PageReports() { + initLayout(); + } + + private void initLayout() { + Form mainForm = new com.evolveum.midpoint.web.component.form.Form(ID_MAIN_FORM); + add(mainForm); + + MainObjectListPanel table = + new MainObjectListPanel(ID_REPORTS_TABLE, ReportType.class, UserProfileStorage.TableId.PAGE_REPORTS, + null) { + + @Override + protected IColumn, String> createCheckboxColumn() { + return null; + } + + @Override + public void objectDetailsPerformed(AjaxRequestTarget target, ReportType report) { + if (report != null) { + PageReports.this.reportDetailsPerformed(target, report.getOid()); + } + } + + @Override + protected List, String>> createColumns() { + return PageReports.this.initColumns(); + } + + @Override + protected List createInlineMenu() { + return PageReports.this.createInlineMenu(); + } + + @Override + protected void newObjectPerformed(AjaxRequestTarget target, AssignmentObjectRelation relation, CompiledObjectCollectionView collectionView) { + navigateToNext(PageNewReport.class); + } + }; + table.setOutputMarkupId(true); + mainForm.add(table); + + } + + private List, String>> initColumns() { + List, String>> columns = new ArrayList<>(); + + IColumn column = new PropertyColumn(createStringResource("PageReports.table.description"), "value.description"); + columns.add(column); + + return columns; + } + + private void reportDetailsPerformed(AjaxRequestTarget target, String oid) { + PageParameters params = new PageParameters(); + params.add(OnePageParameterEncoder.PARAMETER, oid); + navigateToNext(PageCreatedReports.class, params); + } + + private List createInlineMenu(){ + List menu = new ArrayList<>(); + menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.run")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new ColumnMenuAction>() { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + ReportType report = getRowModel().getObject().getValue(); + runReportPerformed(target, report); + } + }; + } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_START_MENU_ITEM; + } + + @Override + public boolean isHeaderMenuItem(){ + return false; + } + }); + menu.add(new ButtonInlineMenuItem(createStringResource("PageReports.button.configure")) { + private static final long serialVersionUID = 1L; + + @Override + public InlineMenuItemAction initAction() { + return new ColumnMenuAction>() { + private static final long serialVersionUID = 1L; + + @Override + public void onClick(AjaxRequestTarget target) { + ReportType reportObject = getRowModel().getObject().getValue(); + configurePerformed(target, reportObject); + } + }; + } + + @Override + public String getButtonIconCssClass() { + return GuiStyleConstants.CLASS_EDIT_MENU_ITEM; + } + + @Override + public boolean isHeaderMenuItem(){ + return false; + } + }); + return menu; + + } + + private void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { + OperationResult result = new OperationResult(OPERATION_RUN_REPORT); + Task task = createSimpleTask(OPERATION_RUN_REPORT); + task.getUpdatedTaskObject().asObjectable().getAssignment() + .add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_REPORT_TASK.value(), ObjectTypes.ARCHETYPE, getPrismContext())); + task.getUpdatedTaskObject().asObjectable().getArchetypeRef() + .add(ObjectTypeUtil.createObjectRef(SystemObjectsType.ARCHETYPE_REPORT_TASK.value(), ObjectTypes.ARCHETYPE)); + try { + getReportManager().runReport(reportType.asPrismObject(), reportParam, task, result); + } catch (Exception ex) { + result.recordFatalError(ex); + } finally { + result.computeStatusIfUnknown(); + } + + showResult(result); + target.add(getFeedbackPanel(), get(createComponentPath(ID_MAIN_FORM))); + hideMainPopup(target); + + } + + protected void runReportPerformed(AjaxRequestTarget target, ReportType report) { + + if(report.getReportEngine() != null && report.getReportEngine().equals(ReportEngineSelectionType.DASHBOARD)) { + runConfirmPerformed(target, report, null); + return; + } + + RunReportPopupPanel runReportPopupPanel = new RunReportPopupPanel(getMainPopupBodyId(), report) { + + private static final long serialVersionUID = 1L; + + protected void runConfirmPerformed(AjaxRequestTarget target, ReportType reportType, PrismContainer reportParam) { + PageReports.this.runConfirmPerformed(target, reportType, reportParam); + hideMainPopup(target); + + }; + }; + showMainPopup(runReportPopupPanel, target); + + } + + private void configurePerformed(AjaxRequestTarget target, ReportType report) { + PageParameters params = new PageParameters(); + params.add(OnePageParameterEncoder.PARAMETER, report.getOid()); + navigateToNext(PageReport.class, params); + } + + private Table getReportTable() { + return (Table) get(createComponentPath(ID_MAIN_FORM, ID_REPORTS_TABLE)); + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java index 5fc8c40919e..71a6fbace29 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java @@ -326,7 +326,7 @@ public boolean isVisible() { initButton(ID_IMPORT, "Import", " fa-download", TaskCategory.IMPORTING_ACCOUNTS, SystemObjectsType.ARCHETYPE_IMPORT_TASK.value()); initButton(ID_RECONCILIATION, "Reconciliation", " fa-link", TaskCategory.RECONCILIATION, SystemObjectsType.ARCHETYPE_RECONCILIATION_TASK.value()); - initButton(ID_LIVE_SYNC, "Live Sync", " fa-refresh", TaskCategory.LIVE_SYNCHRONIZATION, SystemObjectsType.ARCHETYPE_LIVE_SYNCH_TASK.value()); + initButton(ID_LIVE_SYNC, "Live Sync", " fa-refresh", TaskCategory.LIVE_SYNCHRONIZATION, SystemObjectsType.ARCHETYPE_LIVE_SYNC_TASK.value()); initCustomLayout(); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java index 5a4219e3f69..ca1a7621c3a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java @@ -409,6 +409,8 @@ protected static void executeMemberOperation(PageBase modelServiceLocator, Task try { Task executableTask = WebComponentUtil.createMemberOperationTask(operationalTask, type, memberQuery, script, option, parentResult, modelServiceLocator); if (executableTask != null) { + //TODO iterative bulk task archetype +// executableTask.getClonedTaskObject().asObjectable().getAssignment().add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE)) WebComponentUtil.executeMemberOperation(executableTask, parentResult, modelServiceLocator); } } catch (SchemaException e) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.html new file mode 100644 index 00000000000..7c560abdb3b --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.html @@ -0,0 +1,35 @@ + + + + + +

+

+
+ +
+
+
+

+ + +

+ + +

+ + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.java new file mode 100644 index 00000000000..e85fac6d28d --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/LivesyncTokenEditorPanel.java @@ -0,0 +1,173 @@ +/* + * Copyright (c) 2020 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.web.page.admin.server; + +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.delta.builder.S_ValuesEntry; +import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnChangeAjaxFormUpdatingBehavior; + +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.model.IModel; +import org.apache.wicket.model.StringResourceModel; + +import com.evolveum.midpoint.gui.api.component.BasePanel; +import com.evolveum.midpoint.gui.api.model.LoadableModel; +import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; +import com.evolveum.midpoint.gui.impl.prism.PrismPropertyWrapper; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismProperty; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.LoggingUtils; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.AjaxButton; +import com.evolveum.midpoint.web.component.dialog.Popupable; +import com.evolveum.midpoint.web.component.input.TextPanel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; + +public class LivesyncTokenEditorPanel extends BasePanel> implements Popupable { + + private static final transient Trace LOGGER = TraceManager.getTrace(LivesyncTokenEditorPanel.class); + + private static final String ID_TOKEN = "token"; + private static final String ID_OK = "ok"; + private static final String ID_CANCEL = "cancel"; + + private ItemPath tokenPath = ItemPath.create(TaskType.F_EXTENSION, SchemaConstants.SYNC_TOKEN); + + public LivesyncTokenEditorPanel(String id, IModel> model) { + super(id, model); + } + + @Override + protected void onInitialize() { + super.onInitialize(); + initLayout(); + } + + private void initLayout() { + IModel syncTokenModel = new IModel() { + + @Override + public T getObject() { + PrismObjectWrapper taskWrapper = getModelObject(); + PrismObject task = taskWrapper.getObject(); + PrismProperty token = task.findProperty(tokenPath); + + if (token == null) { + return null; + } + + return token.getRealValue(); + } + + @Override + public void setObject(T object) { + PrismObjectWrapper taskWrapper = getModelObject(); + PrismObject task = taskWrapper.getObject(); + PrismProperty token = task.findProperty(tokenPath); + + if (token == null) { + try { + token = task.findOrCreateProperty(tokenPath); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot create token property", e); + getSession().error("Cannot create token property: " + e.getMessage()); + return; + } + } + + token.setRealValue(object); + } + }; + + TextPanel tokenPanel = new TextPanel<>(ID_TOKEN, syncTokenModel); + tokenPanel.getBaseFormComponent().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); + add(tokenPanel); + + AjaxButton okButton = new AjaxButton(ID_OK, createStringResource("button.ok")) { + + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + getPageBase().hideMainPopup(ajaxRequestTarget); + ObjectDelta tokenDelta = getTokenDelta(ajaxRequestTarget); + if (tokenDelta == null) { + getSession().warn("Nothing to save. Token was not changed"); + return; + } + saveTokenPerformed(tokenDelta, ajaxRequestTarget); + } + }; + add(okButton); + + AjaxButton cancelButton = new AjaxButton(ID_CANCEL, createStringResource("button.cancel")) { + + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + getPageBase().hideMainPopup(ajaxRequestTarget); + } + }; + add(cancelButton); + } + + private ObjectDelta getTokenDelta(AjaxRequestTarget target) { + TextPanel tokenPanel = (TextPanel)get(ID_TOKEN); + T newTokenValue = tokenPanel.getBaseFormComponent().getModelObject(); + try { + PrismProperty tokenProperty = getModelObject().getObject().findProperty(tokenPath); + + S_ValuesEntry valuesEntry = getPrismContext().deltaFor(TaskType.class).item(tokenPath, tokenProperty.getDefinition()); + if (newTokenValue == null) { + return valuesEntry.replace().asObjectDelta(getModelObject().getOid()); + } + return valuesEntry.replace(newTokenValue).asObjectDelta(getModelObject().getOid()); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot modify token", e); + getSession().error("Cannot modify token: " + e.getMessage()); + target.add(getPageBase().getFeedbackPanel()); + return null; + } + } + + protected void saveTokenPerformed(ObjectDelta tokenDelta, AjaxRequestTarget target) { + + } + + @Override + public int getWidth() { + return 400; + } + + @Override + public int getHeight() { + return 200; + } + + @Override + public String getWidthUnit() { + return "px"; + } + + @Override + public String getHeightUnit() { + return "px"; + } + + @Override + public StringResourceModel getTitle() { + return createStringResource("LivesyncTokenEditorPanel.manage.token"); + } + + @Override + public Component getComponent() { + return this; + } +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java index 1d74f22a604..039aaecd5eb 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java @@ -1,8 +1,18 @@ package com.evolveum.midpoint.web.page.admin.server; +import java.io.InputStream; import java.util.Collection; import java.util.Collections; +import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; +import com.evolveum.midpoint.report.api.ReportConstants; +import com.evolveum.midpoint.report.api.ReportManager; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.web.component.AjaxDownloadBehaviorFromStream; +import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; + +import com.evolveum.midpoint.web.page.admin.reports.PageCreatedReports; + import org.apache.wicket.Component; import org.apache.wicket.Page; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -65,6 +75,7 @@ public class PageTask extends PageAdminObjectDetails implements Refres private static final transient Trace LOGGER = TraceManager.getTrace(PageTask.class); private static final String DOT_CLASS = PageTask.class.getName() + "."; protected static final String OPERATION_EXECUTE_TASK_CHANGES = DOT_CLASS + "executeTaskChanges"; + private static final String OPERATION_LOAD_REPORT_OUTPUT = DOT_CLASS + "loadReport"; private static final int REFRESH_INTERVAL = 2000; @@ -124,6 +135,42 @@ private void afterOperation(AjaxRequestTarget target, OperationResult result) { protected void initOperationalButtons(RepeatingView repeatingView) { super.initOperationalButtons(repeatingView); + + createSuspendButton(repeatingView); + createResumeButton(repeatingView); + createRunNowButton(repeatingView); + + createManageLivesyncTokenButton(repeatingView); + createDownloadReportButton(repeatingView); + createCleanupPerformanceButton(repeatingView); + createCleanupResultsButton(repeatingView); + + createRefreshNowIconButton(repeatingView); + createResumePauseButton(repeatingView); + + + +// AjaxIconButton cleanupErrors = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), +// createStringResource("operationalButtonsPanel.cleanupErrors")) { +// +// @Override +// public void onClick(AjaxRequestTarget target) { +// refresh(target); +// } +// }; +// cleanupErrors.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); +// cleanupErrors.add(new VisibleBehaviour(this::isNotRunning)); +// repeatingView.add(cleanupErrors); + + setOutputMarkupId(true); + + final Label status = new Label(repeatingView.newChildId(), this::createRefreshingLabel); + status.setOutputMarkupId(true); + repeatingView.add(status); + + } + + private void createSuspendButton(RepeatingView repeatingView) { AjaxButton suspend = new AjaxButton(repeatingView.newChildId(), createStringResource("pageTaskEdit.button.suspend")) { @Override public void onClick(AjaxRequestTarget target) { @@ -135,7 +182,9 @@ public void onClick(AjaxRequestTarget target) { suspend.add(new VisibleBehaviour(() -> WebComponentUtil.canSuspendTask(getTask(), PageTask.this))); suspend.add(AttributeAppender.append("class", "btn-danger")); repeatingView.add(suspend); + } + private void createResumeButton(RepeatingView repeatingView) { AjaxButton resume = new AjaxButton(repeatingView.newChildId(), createStringResource("pageTaskEdit.button.resume")) { @Override public void onClick(AjaxRequestTarget target) { @@ -147,7 +196,9 @@ public void onClick(AjaxRequestTarget target) { resume.add(AttributeAppender.append("class", "btn-primary")); resume.add(new VisibleBehaviour(() -> WebComponentUtil.canResumeTask(getTask(), PageTask.this))); repeatingView.add(resume); + } + private void createRunNowButton(RepeatingView repeatingView) { AjaxButton runNow = new AjaxButton(repeatingView.newChildId(), createStringResource("pageTaskEdit.button.runNow")) { @Override public void onClick(AjaxRequestTarget target) { @@ -160,7 +211,113 @@ public void onClick(AjaxRequestTarget target) { runNow.add(AttributeAppender.append("class", "btn-success")); runNow.add(new VisibleBehaviour(() -> WebComponentUtil.canRunNowTask(getTask(), PageTask.this))); repeatingView.add(runNow); + } + + private void createManageLivesyncTokenButton(RepeatingView repeatingView) { + AjaxButton manageLivesyncToken = new AjaxButton(repeatingView.newChildId(), createStringResource("PageTask.livesync.token")) { + + @Override + public void onClick(AjaxRequestTarget ajaxRequestTarget) { + LivesyncTokenEditorPanel tokenEditor = new LivesyncTokenEditorPanel(PageTask.this.getMainPopupBodyId(), getObjectModel()) { + + @Override + protected void saveTokenPerformed(ObjectDelta tokenDelta, AjaxRequestTarget target) { + saveTaskChanges(target, tokenDelta); + } + }; + tokenEditor.setOutputMarkupId(true); + PageTask.this.showMainPopup(tokenEditor, ajaxRequestTarget); + } + }; + manageLivesyncToken.add(new VisibleEnableBehaviour() { + @Override + public boolean isVisible() { + return WebComponentUtil.isLiveSync(getTask()) && isNotRunning(); + } + + @Override + public boolean isEnabled() { + return isNotRunning(); + } + }); + manageLivesyncToken.add(AttributeAppender.append("class", "btn-default")); + manageLivesyncToken.setOutputMarkupId(true); + repeatingView.add(manageLivesyncToken); + } + + private void createDownloadReportButton(RepeatingView repeatingView) { + final AjaxDownloadBehaviorFromStream ajaxDownloadBehavior = new AjaxDownloadBehaviorFromStream() { + private static final long serialVersionUID = 1L; + + @Override + protected InputStream initStream() { + ReportOutputType reportObject = getReportOutput(); + if (reportObject != null) { + return PageCreatedReports.createReport(reportObject, this, PageTask.this); + } else { + return null; + } + } + + + @Override + public String getFileName() { + ReportOutputType reportObject = getReportOutput(); + return PageCreatedReports.getReportFileName(reportObject); + } + }; + add(ajaxDownloadBehavior); + + AjaxButton download = new AjaxButton(repeatingView.newChildId(), createStringResource("PageTask.download.report")) { + + private static final long serialVersionUID = 1L; + @Override + public void onClick(AjaxRequestTarget target) { + ajaxDownloadBehavior.initiate(target); + } + }; + download.add(new VisibleBehaviour(() -> isDownloadReportVisible())); + download.add(AttributeAppender.append("class", "btn-primary")); + repeatingView.add(download); + } + + private boolean isDownloadReportVisible() { + return WebComponentUtil.isReport(getTask()) + && getReportOutputProperty() != null; + } + + private ReportOutputType getReportOutput() { + PrismProperty reportOutput = getReportOutputProperty(); + if (reportOutput == null) { + return null; + } + + String reportOutputOid = reportOutput.getRealValue(); + if (reportOutputOid == null) { + return null; + } + + Task opTask = createSimpleTask(OPERATION_LOAD_REPORT_OUTPUT); + OperationResult result = opTask.getResult(); + + PrismObject report = WebModelServiceUtils.loadObject(ReportOutputType.class, reportOutputOid, this, opTask, result); + if (report == null) { + return null; + } + result.computeStatusIfUnknown(); + showResult(result, false); + + return report.asObjectable(); + + } + + private PrismProperty getReportOutputProperty() { + PrismObject task = getTask().asPrismObject(); + return task.findProperty(ItemPath.create(TaskType.F_EXTENSION, ReportConstants.REPORT_OUTPUT_OID_PROPERTY_NAME)); + } + + private void createRefreshNowIconButton(RepeatingView repeatingView) { AjaxIconButton refreshNow = new AjaxIconButton(repeatingView.newChildId(), new Model<>("fa fa-refresh"), createStringResource("autoRefreshPanel.refreshNow")) { @Override @@ -170,8 +327,10 @@ public void onClick(AjaxRequestTarget target) { }; refreshNow.add(AttributeAppender.append("class", "btn btn-default btn-sm")); repeatingView.add(refreshNow); + } - AjaxIconButton resumePauseRefreshing = new AjaxIconButton(repeatingView.newChildId(), (IModel) this::createResumePauseButton, createStringResource("autoRefreshPanel.resumeRefreshing")) { + private void createResumePauseButton(RepeatingView repeatingView) { + AjaxIconButton resumePauseRefreshing = new AjaxIconButton(repeatingView.newChildId(), (IModel) this::createResumePauseButtonLabel, createStringResource("autoRefreshPanel.resumeRefreshing")) { @Override public void onClick(AjaxRequestTarget target) { @@ -181,7 +340,9 @@ public void onClick(AjaxRequestTarget target) { }; resumePauseRefreshing.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); repeatingView.add(resumePauseRefreshing); + } + private void createCleanupPerformanceButton(RepeatingView repeatingView) { AjaxIconButton cleanupPerformance = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), createStringResource("operationalButtonsPanel.cleanupEnvironmentalPerformance")) { @@ -193,14 +354,15 @@ public void onClick(AjaxRequestTarget target) { } catch (SchemaException e){ LOGGER.error("Cannot clear task results: {}", e.getMessage()); } - saveTaskChanges(); - refresh(target); + saveTaskChanges(target); } }; cleanupPerformance.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); cleanupPerformance.add(new VisibleBehaviour(this::isNotRunning)); repeatingView.add(cleanupPerformance); + } + private void createCleanupResultsButton(RepeatingView repeatingView) { AjaxIconButton cleanupResults = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), createStringResource("operationalButtonsPanel.cleanupResults")) { @@ -212,49 +374,46 @@ public void onClick(AjaxRequestTarget target) { } catch (SchemaException e){ LOGGER.error("Cannot clear task results: {}", e.getMessage()); } - saveTaskChanges(); + saveTaskChanges(target); refresh(target); } }; cleanupResults.add(new VisibleBehaviour(this::isNotRunning)); cleanupResults.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); repeatingView.add(cleanupResults); + } -// AjaxIconButton cleanupErrors = new AjaxIconButton(repeatingView.newChildId(), new Model<>(GuiStyleConstants.CLASS_ICON_TRASH), -// createStringResource("operationalButtonsPanel.cleanupErrors")) { -// -// @Override -// public void onClick(AjaxRequestTarget target) { -// refresh(target); -// } -// }; -// cleanupErrors.add(AttributeAppender.append("class", "btn btn-default btn-margin-left btn-sm")); -// cleanupErrors.add(new VisibleBehaviour(this::isNotRunning)); -// repeatingView.add(cleanupErrors); - - setOutputMarkupId(true); - - final Label status = new Label(repeatingView.newChildId(), this::createRefreshingLabel); - status.setOutputMarkupId(true); - repeatingView.add(status); - + private void saveTaskChanges(AjaxRequestTarget target) { + try { + ObjectDelta taskDelta = getObjectWrapper().getObjectDelta(); + saveTaskChanges(target, taskDelta); + } catch (SchemaException e) { + LoggingUtils.logUnexpectedException(LOGGER, "Cannot get task delta.", e); + getSession().error("Cannot save changes, there were problems with computing changes: " + e.getMessage()); + target.add(getFeedbackPanel()); + } } - private void saveTaskChanges(){ + private void saveTaskChanges(AjaxRequestTarget target, ObjectDelta taskDelta){ + if (taskDelta.isEmpty()) { + getSession().warn("Nothing to save, no changes were made."); + return; + } + OperationResult result = new OperationResult(OPERATION_EXECUTE_TASK_CHANGES); Task task = createSimpleTask(OPERATION_EXECUTE_TASK_CHANGES); + try { - ObjectDelta taskDelta = getObjectWrapper().getObjectDelta(); - if (!taskDelta.isEmpty()) { - taskDelta.revive(getPrismContext()); - getModelService().executeChanges(MiscUtil.createCollection(taskDelta), null, task, result); - result.computeStatus(); - getObjectModel().reset(); - } + taskDelta.revive(getPrismContext()); //do we need revive here? + getModelService().executeChanges(MiscUtil.createCollection(taskDelta), null, task, result); + result.computeStatus(); + getObjectModel().reset(); } catch (Exception e) { - LOGGER.error("Cannot save tasks changes: {}", e.getMessage()); + LoggingUtils.logUnexpectedException(LOGGER, "Cannot save tasks changes", e); + result.recordFatalError("Cannot save tasks changes, " + e.getMessage(), e); } - showResult(result); +// showResult(result); + afterOperation(target, result); } public void saveAndRunPerformed(AjaxRequestTarget target) { @@ -306,7 +465,7 @@ private String createRefreshingLabel() { } } - private String createResumePauseButton() { + private String createResumePauseButtonLabel() { if (isRefreshEnabled()) { return "fa fa-pause"; } @@ -354,6 +513,7 @@ public int getRefreshInterval() { public void refresh(AjaxRequestTarget target) { + getObjectModel().reset(); target.add(getSummaryPanel()); target.add(getOperationalButtonsPanel()); target.add(getFeedbackPanel()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java index d84ffd0b0ea..dbcb2242ac4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java @@ -82,13 +82,14 @@ public boolean computeSubtasksAndThreadsVisible(PageTask parentPage, PrismObject } public boolean configuresWorkerThreads(TaskType task) { - return isReconciliation(task) || isImport(task) || isRecomputation(task) || isExecuteChanges(task.getHandlerUri()) + return WebComponentUtil.isReconciliation(task) || WebComponentUtil.isImport(task) || WebComponentUtil.isRecomputation(task) || isExecuteChanges(task.getHandlerUri()) || isShadowIntegrityCheck(task.getHandlerUri()) || isFocusValidityScanner(task.getHandlerUri()) || isTriggerScanner(task.getHandlerUri()); } public boolean computeEnvironmentalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { final OperationStatsType operationStats = taskWrapper.getObject().asObjectable().getOperationStats(); environmentalPerformanceVisible = parentPage.isEditingFocus(); + //todo does it make sense to check operationStats? it may be null for partitioned task // && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) // && operationStats != null // && !StatisticsUtil.isEmpty(operationStats.getEnvironmentalPerformanceInformation()); @@ -97,6 +98,7 @@ public boolean computeEnvironmentalPerformanceVisible(PageTask parentPage, Prism public boolean computeInternalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { internalPerformanceVisible = parentPage.isEditingFocus(); + //todo doea it make sense to check operationStats? it may be null for partitioned task // && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) // && taskWrapper.getObject().asObjectable().getOperationStats() != null; return internalPerformanceVisible; @@ -165,44 +167,6 @@ private boolean isExecuteChanges(String handlerUri) { return ModelPublicConstants.EXECUTE_CHANGES_TASK_HANDLER_URI.equals(handlerUri); } - private boolean isReconciliation(TaskType task){ - ObjectReferenceType archetypeRef = getArchetypeReference(task); - if (archetypeRef == null){ - return false; - } - return SystemObjectsType.ARCHETYPE_RECONCILIATION_TASK.value().equals(archetypeRef.getOid()); - } - - private boolean isRecomputation(TaskType task){ - ObjectReferenceType archetypeRef = getArchetypeReference(task); - if (archetypeRef == null){ - return false; - } - return SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value().equals(archetypeRef.getOid()); - } - - private boolean isImport(TaskType task){ - ObjectReferenceType archetypeRef = getArchetypeReference(task); - if (archetypeRef == null){ - return false; - } - return SystemObjectsType.ARCHETYPE_IMPORT_TASK.value().equals(archetypeRef.getOid()); - } - - private ObjectReferenceType getArchetypeReference(TaskType task) { - ObjectReferenceType archetypeRef = null; - if (task.getAssignment() == null || task.getAssignment().size() == 0) { - return archetypeRef; - } - for (AssignmentType assignment : task.getAssignment()) { - if (StringUtils.isNotEmpty(assignment.getTargetRef().getOid()) - && assignment.getTargetRef() != null && QNameUtil.match(assignment.getTargetRef().getType(), ArchetypeType.COMPLEX_TYPE)) { - archetypeRef = assignment.getTargetRef(); - } - } - return archetypeRef; - } - private boolean isTaskItemReadable(PrismObjectWrapper taskWrapper, ItemPath itemPath){ ItemWrapper taskProperty = null; try { diff --git a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd index 7534e40b98b..7bbd75ae1fc 100755 --- a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd +++ b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd @@ -21479,7 +21479,14 @@ - + + + + + + + + From 83fd0be68a814fbf9c106b38eed8c3f90c84c017 Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Sun, 8 Mar 2020 23:43:01 +0100 Subject: [PATCH 27/55] iterative bulk archetype for member operations - assign/unassign --- .../web/page/admin/roles/MemberOperationsHelper.java | 11 +++++++++-- .../web/page/admin/server/TaskTablePanel.java | 1 + .../resources/xml/ns/public/common/common-core-3.xsd | 7 +++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java index ca1a7621c3a..16f0e867599 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java @@ -18,6 +18,7 @@ import com.evolveum.midpoint.gui.api.component.ChooseArchetypeMemberPopup; import com.evolveum.midpoint.prism.query.QueryFactory; import com.evolveum.midpoint.prism.query.builder.S_FilterEntry; +import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -146,6 +147,10 @@ public static Task createRecomputeMembersTask(PageB Task operationalTask = pageBase.createSimpleTask(getTaskName(RECOMPUTE_OPERATION, scope)); OperationResult parentResult = operationalTask.getResult(); try { + operationalTask.getClonedTaskObject().asObjectable().getAssignment() + .add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value(), ObjectTypes.ARCHETYPE, pageBase.getPrismContext())); + operationalTask.getClonedTaskObject().asObjectable().getArchetypeRef() + .add(ObjectTypeUtil.createObjectRef(SystemObjectsType.ARCHETYPE_RECOMPUTATION_TASK.value(), ObjectTypes.ARCHETYPE)); return WebComponentUtil.createRecomputeMemberOperationTask(operationalTask, AssignmentHolderType.COMPLEX_TYPE, query, null, parentResult, pageBase); } catch (SchemaException e) { @@ -409,8 +414,10 @@ protected static void executeMemberOperation(PageBase modelServiceLocator, Task try { Task executableTask = WebComponentUtil.createMemberOperationTask(operationalTask, type, memberQuery, script, option, parentResult, modelServiceLocator); if (executableTask != null) { - //TODO iterative bulk task archetype -// executableTask.getClonedTaskObject().asObjectable().getAssignment().add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE)) + executableTask.getUpdatedTaskObject().asObjectable().getAssignment() + .add(ObjectTypeUtil.createAssignmentTo(SystemObjectsType.ARCHETYPE_ITERATIVE_BULK_ACTION_TASK.value(), ObjectTypes.ARCHETYPE, modelServiceLocator.getPrismContext())); + executableTask.getUpdatedTaskObject().asObjectable().getArchetypeRef() + .add(ObjectTypeUtil.createObjectRef(SystemObjectsType.ARCHETYPE_ITERATIVE_BULK_ACTION_TASK.value(), ObjectTypes.ARCHETYPE)); WebComponentUtil.executeMemberOperation(executableTask, parentResult, modelServiceLocator); } } catch (SchemaException e) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java index f334c8330c8..1c61d996ac4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java @@ -699,6 +699,7 @@ public IModel getConfirmationMessageModel() { } //region Task-level actions + //TODO unify with TaskOperationUtils private void suspendTasksPerformed(AjaxRequestTarget target, IModel> selectedTask) { List selectedTasks = getSelectedTasks(target, selectedTask); if (selectedTasks == null) { diff --git a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd index 7bbd75ae1fc..4fa8bbb8464 100755 --- a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd +++ b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd @@ -21490,6 +21490,13 @@ + + + + + + + From f4bd73b8eee87fe437a3f3cc624ec4475350a702 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Sun, 8 Mar 2020 20:32:01 +0100 Subject: [PATCH 28/55] more test cleanup, more TEST_NAME variables gone (default tests pass) --- .../midpoint/schema/TestQueryConverter.java | 13 +- .../schema/validator/TestObjectValidator.java | 16 +- .../test/AbstractModelIntegrationTest.java | 5 +- .../TestConfiguredCapabilitiesActivation.java | 6 - .../story/TestConsistencyMechanism.java | 151 +++++---------- .../testing/story/TestDelayedEnable.java | 175 +++++------------- .../testing/story/TestDependencyRename.java | 12 +- .../story/ldap/TestLdapVirtualGroup.java | 63 +------ 8 files changed, 112 insertions(+), 329 deletions(-) diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java index 49fc0d62ab0..20351d533c1 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/TestQueryConverter.java @@ -700,12 +700,13 @@ public void test700Exists() throws Exception { checkQueryRoundtripFile(AccessCertificationCaseType.class, q); } + public static final String TEST_900_910_FILE_NAME = TEST_DIR + "/test900TypeWrong.xml"; + @Test public void test900TypeWrong() throws Exception { - final String TEST_NAME = "test900TypeWrong"; - String fileName = TEST_DIR + "/" + TEST_NAME + ".xml"; try { - toQueryType(FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8)); + toQueryType(FileUtils.readFileToString( + new File(TEST_900_910_FILE_NAME), StandardCharsets.UTF_8)); fail("Unexpected success!"); } catch (SchemaException e) { System.out.println("Got expected exception: " + e.getMessage()); @@ -714,10 +715,8 @@ public void test900TypeWrong() throws Exception { @Test public void test910TypeWrongCompat() throws Exception { - final String TEST_NAME = "test900TypeWrong"; - String fileName = TEST_DIR + "/" + TEST_NAME + ".xml"; - QueryType jaxb = toQueryTypeCompat( - FileUtils.readFileToString(new File(fileName), StandardCharsets.UTF_8)); + QueryType jaxb = toQueryTypeCompat(FileUtils.readFileToString( + new File(TEST_900_910_FILE_NAME), StandardCharsets.UTF_8)); displayQueryType(jaxb); try { ObjectQuery query = toObjectQuery(ObjectType.class, jaxb); diff --git a/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java b/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java index 5e8c981d17b..9d5ef0378b8 100644 --- a/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java +++ b/infra/schema/src/test/java/com/evolveum/midpoint/schema/validator/TestObjectValidator.java @@ -25,7 +25,6 @@ /** * @author semancik - * */ public class TestObjectValidator extends AbstractSchemaTest { @@ -41,10 +40,7 @@ public class TestObjectValidator extends AbstractSchemaTest { @Test public void testValidateRoleOneDefault() throws Exception { - final String TEST_NAME = "testValidateRoleOneDefault"; - // GIVEN - ObjectValidator validator = createValidator(); PrismObject object = PrismTestUtil.getPrismContext().parseObject(ROLE_ONE_FILE); @@ -63,8 +59,6 @@ public void testValidateRoleOneDefault() throws Exception { @Test public void testValidateRoleOneDeprecated() throws Exception { - final String TEST_NAME = "testValidateRoleOneDeprecated"; - // GIVEN ObjectValidator validator = createValidator(); @@ -90,8 +84,6 @@ public void testValidateRoleOneDeprecated() throws Exception { */ @Test public void testValidateRoleOneLegacyCompat() throws Exception { - final String TEST_NAME = "testValidateRoleOneLegacyCompat"; - // GIVEN ObjectValidator validator = createValidator(); @@ -120,8 +112,6 @@ public void testValidateRoleOneLegacyCompat() throws Exception { */ @Test public void testValidateRoleOneLegacyStrict() throws Exception { - final String TEST_NAME = "testValidateRoleOneLegacyStrict"; - // GIVEN ObjectValidator validator = createValidator(); @@ -144,11 +134,7 @@ public void testValidateRoleOneLegacyStrict() throws Exception { // We have no planned removal annotations in 4.0. Nothing to test. // @Test // public void testValidateRoleOnePlannedRemoval() throws Exception { -// final String TEST_NAME = "testValidateRoleOnePlannedRemoval"; -// displayTestTile(TEST_NAME); -// // // GIVEN -// // ObjectValidator validator = createValidator(); // validator.setWarnPlannedRemoval(true); // @@ -179,7 +165,7 @@ private void assertWarnings(ValidationResult validationResult, Object... expecte if (expectedItem instanceof ItemPath) { expectedPath = (ItemPath)expectedItem; } else if (expectedItem instanceof QName) { - expectedPath = ItemPath.create((QName)expectedItem); + expectedPath = ItemPath.create(expectedItem); } else { throw new IllegalArgumentException("What? "+expectedItem); } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index e7df8dbb191..8684b46f894 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -5976,10 +5976,7 @@ protected ShadowAsserter assertModelShadow(String oid) throws ObjectNotFou protected ShadowAsserter assertModelShadowNoFetch(String oid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject repoShadow = getShadowModelNoFetch(oid); - ShadowAsserter asserter = ShadowAsserter.forShadow(repoShadow, "model(noFetch)"); - asserter - .display(); - return asserter; + return ShadowAsserter.forShadow(repoShadow, "model(noFetch)").display(); } protected ShadowAsserter assertModelShadowFuture(String oid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java index 65a2d3a6cd0..cc0e25a7b0d 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConfiguredCapabilitiesActivation.java @@ -80,8 +80,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ImportAccount() throws Exception { - final String TEST_NAME = "test100ImportAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -104,8 +102,6 @@ public void test100ImportAccount() throws Exception { @Test public void test110AssignJackPirate() throws Exception { - String TEST_NAME = "test110AssignJackPirate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -164,8 +160,6 @@ public void test110AssignJackPirate() throws Exception { @Test public void test112ModifyActivationJack() throws Exception { - String TEST_NAME = "test112ModifyActivationJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java index 1f95834e186..a111fc2782a 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java @@ -90,21 +90,18 @@ public class TestConsistencyMechanism extends AbstractModelIntegrationTest { private static final String SYSTEM_CONFIGURATION_FILENAME = TEST_DIR + "system-configuration.xml"; private static final String ROLE_SUPERUSER_FILENAME = TEST_DIR + "role-superuser.xml"; - private static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004"; private static final String ROLE_LDAP_ADMINS_FILENAME = TEST_DIR + "role-admins.xml"; private static final String ROLE_LDAP_ADMINS_OID = "88888888-8888-8888-8888-000000000009"; private static final String ROLE_LDAP_ADMINS_DN = "cn=admins,ou=groups,dc=example,dc=com"; private static final String SAMPLE_CONFIGURATION_OBJECT_FILENAME = TEST_DIR + "sample-configuration-object.xml"; - private static final String SAMPLE_CONFIGURATION_OBJECT_OID = "c0c010c0-d34d-b33f-f00d-999111111111"; private static final String RESOURCE_OPENDJ_FILENAME = TEST_DIR + "resource-opendj.xml"; private static final String RESOURCE_OPENDJ_OID = "ef2bc95b-76e0-59e2-86d6-3d4f02d3ffff"; private static final String RESOURCE_OPENDJ_NS = "http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; private static final QName RESOURCE_OPENDJ_ACCOUNT_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS, "inetOrgPerson"); private static final QName RESOURCE_OPENDJ_GROUP_OBJECTCLASS = new QName(RESOURCE_OPENDJ_NS, "groupOfUniqueNames"); - private static final String RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME = "entryUUID"; private static final String RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME = "dn"; private static final QName RESOURCE_OPENDJ_SECONDARY_IDENTIFIER = new QName(RESOURCE_OPENDJ_NS, RESOURCE_OPENDJ_SECONDARY_IDENTIFIER_LOCAL_NAME); @@ -232,7 +229,6 @@ public class TestConsistencyMechanism extends AbstractModelIntegrationTest { private static final QName LDAP_ATTRIBUTE_EMPLOYEE_TYPE = new ItemName(MidPointConstants.NS_RI, "employeeType"); private static ResourceType resourceTypeOpenDjrepo; - private static String accountShadowOidOpendj; private String aliceAccountDn; // This will get called from the superclass to init the repository @@ -330,8 +326,6 @@ public void test000Integrity() throws Exception { */ @Test public void test001TestConnectionOpenDJ() throws Exception { - final String TEST_NAME = "test001TestConnectionOpenDJ"; - Task task = taskManager.createTaskInstance(); // GIVEN @@ -348,8 +342,7 @@ public void test001TestConnectionOpenDJ() throws Exception { TestUtil.assertSuccess("testResource has failed", result); - OperationResult opResult = new OperationResult(TestConsistencyMechanism.class.getName() - + "." + TEST_NAME); + OperationResult opResult = createOperationResult(); PrismObject resourceOpenDjRepo = repositoryService.getObject(ResourceType.class, RESOURCE_OPENDJ_OID, null, opResult); @@ -390,9 +383,7 @@ public void test001TestConnectionOpenDJ() throws Exception { */ @Test public void test100AddUser() throws Exception { - final String TEST_NAME = "test100AddUser"; - - UserType userType = testAddUserToRepo(TEST_NAME, USER_JACK_FILENAME, USER_JACK_OID); + UserType userType = testAddUserToRepo(USER_JACK_FILENAME); OperationResult repoResult = new OperationResult("getObject"); @@ -428,8 +419,6 @@ public void test110PrepareOpenDjWithJackieAccounts() throws Exception { ReferenceDelta linkRefDelta = prismContext.deltaFactory().reference().createModificationAdd(UserType.class, UserType.F_LINK_REF, ObjectTypeUtil.createObjectRef(jackieAccount, SchemaConstants.ORG_DEFAULT).asReferenceValue()); repositoryService.modifyObject(UserType.class, USER_JACK_OID, Arrays.asList(linkRefDelta), parentResult); - OperationResult repoResult = new OperationResult("getObject"); - // Check if user object was modified in the repo assertUserOneAccountRef(USER_JACK_OID); @@ -579,8 +568,8 @@ public void test122AddAccountAlreadyExistUnlinked() throws Exception { String dn = searchResult.getDN().toString(); assertEquals("DN attribute " + dn + " not equals", dn, "uid=wturner,ou=People,dc=example,dc=com"); - testAddUserToRepo("test122AddAccountAlreadyExistUnlinked", USER_WILL_FILENAME, - USER_WILL_OID); + testAddUserToRepo(USER_WILL_FILENAME + ); assertUserNoAccountRef(USER_WILL_OID, parentResult); Task task = taskManager.createTaskInstance(); @@ -744,7 +733,6 @@ public void test130DeleteObjectNotFound() throws Exception { *

* no assignemnt - only linkRef to non existent account */ - @SuppressWarnings("unchecked") @Test public void test140ModifyObjectNotFoundLinkedAccount() throws Exception { Task task = getTestTask(); @@ -885,7 +873,7 @@ public void test144GetObjectNotFoundAssignedAccount() throws Exception { Task task = taskManager.createTaskInstance(); //WHEN - PrismObject modificatedUser = modelService.getObject(UserType.class, USER_HECTOR_NOT_FOUND_OID, null, task, parentResult); + PrismObject modifiedUser = modelService.getObject(UserType.class, USER_HECTOR_NOT_FOUND_OID, null, task, parentResult); // THEN PrismObject userAfter = getUser(USER_HECTOR_NOT_FOUND_OID); @@ -1095,11 +1083,9 @@ public void test210AddObjectCommunicationProblem() throws Exception { @SuppressWarnings("unchecked") @Test public void test212AddModifyObjectCommunicationProblem() throws Exception { - final String TEST_NAME = "test212AddModifyObjectCommunicationProblem"; - // GIVEN openDJController.assumeStopped(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult parentResult = task.getResult(); assertUser(USER_E_OID, "User before").assertLinks(1); @@ -1120,7 +1106,7 @@ public void test212AddModifyObjectCommunicationProblem() throws Exception { //THEN then(); assertRepoShadow(accountOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + "Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertIsNotExists() .assertNotDead() @@ -1166,8 +1152,6 @@ private ItemPath createAttributePath(QName itemName) { @Test public void test214ModifyObjectCommunicationProblem() throws Exception { - final String TEST_NAME = "test214ModifyObjectCommunicationProblem"; - // GIVEN openDJController.assumeStopped(); OperationResult parentResult = createOperationResult(); @@ -1191,7 +1175,7 @@ public void test214ModifyObjectCommunicationProblem() throws Exception { //THEN then(); assertModelShadowNoFetch(ACCOUNT_JACKIE_OID) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + ".Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertNotDead() .assertNoLegacyConsistency() @@ -1228,14 +1212,14 @@ public void test214ModifyObjectCommunicationProblem() throws Exception { @Test public void test220DeleteObjectCommunicationProblem() throws Exception { - final String TEST_NAME = "test220DeleteObjectCommunicationProblem"; + final String testName = getTestNameShort(); // GIVEN openDJController.assumeStopped(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = taskManager.createTaskInstance(testName); OperationResult parentResult = task.getResult(); - String accountOid = assertUserOneAccountRef(USER_DENIELS_OID); + assertUserOneAccountRef(USER_DENIELS_OID); //WHEN ObjectDelta deleteDelta = prismContext.deltaFactory().object().createDeleteDelta(ShadowType.class, ACCOUNT_DENIELS_OID); @@ -1244,12 +1228,12 @@ public void test220DeleteObjectCommunicationProblem() throws Exception { executeChanges(deleteDelta, null, task, parentResult); XMLGregorianCalendar lastRequestEndTs = clock.currentTimeXMLGregorianCalendar(); - assertUser(USER_DENIELS_OID, TEST_NAME) + assertUser(USER_DENIELS_OID, testName) .assertLinks(1); // THEN assertModelShadowNoFetch(ACCOUNT_DENIELS_OID) - .display(TEST_NAME + "Shadow after") + .display(testName + "Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertNotDead() .assertNoLegacyConsistency() @@ -1278,7 +1262,7 @@ public void test220DeleteObjectCommunicationProblem() throws Exception { @Test public void test230GetAccountCommunicationProblem() throws Exception { - final String TEST_NAME = "test230GetAccountCommunicationProblem"; + final String testName = getTestNameShort(); // GIVEN openDJController.assumeStopped(); @@ -1290,7 +1274,7 @@ public void test230GetAccountCommunicationProblem() throws Exception { assertNotNull("Fetch result was not set in the shadow.", account.getFetchResult()); assertModelShadowNoFetch(ACCOUNT_DENIELS_OID) - .display(TEST_NAME + "Shadow after") + .display(testName + "Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertNotDead() .assertNoLegacyConsistency() @@ -1313,13 +1297,11 @@ public void test230GetAccountCommunicationProblem() throws Exception { @Test public void test240AddObjectCommunicationProblemAlreadyExists() throws Exception { - final String TEST_NAME = "test240AddObjectCommunicationProblemAlreadyExists"; - // GIVEN openDJController.assumeRunning(); OperationResult parentResult = createOperationResult(); - Entry entry = openDJController.addEntryFromLdifFile(LDIF_ELAINE_FILE); + openDJController.addEntryFromLdifFile(LDIF_ELAINE_FILE); Entry searchResult = openDJController.searchByUid("elaine"); OpenDJController.assertAttribute(searchResult, "l", "Caribbean"); OpenDJController.assertAttribute(searchResult, "givenName", "Elaine"); @@ -1355,7 +1337,7 @@ public void test240AddObjectCommunicationProblemAlreadyExists() throws Exception String shadowOid = getLinkRefOid(USER_ELAINE_OID, RESOURCE_OPENDJ_OID); assertRepoShadow(shadowOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + ".Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertIsNotExists() .assertNotDead() @@ -1386,8 +1368,6 @@ public void test240AddObjectCommunicationProblemAlreadyExists() throws Exception @Test public void test250ModifyFocusCommunicationProblem() throws Exception { - final String TEST_NAME = "test250ModifyFocusCommunicationProblem"; - // GIVEN openDJController.assumeStopped(); OperationResult parentResult = createOperationResult(); @@ -1427,7 +1407,7 @@ public void test250ModifyFocusCommunicationProblem() throws Exception { String shadowOid = getLinkRefOid(USER_JACKIE_OID, RESOURCE_OPENDJ_OID); assertModelShadowNoFetch(shadowOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + "Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertNotDead() .assertNoLegacyConsistency() @@ -1460,13 +1440,10 @@ public void test250ModifyFocusCommunicationProblem() throws Exception { .end() .assertIsExists() .end(); - } @Test public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception { - final String TEST_NAME = "test251ModifyFocusCommunicationProblemSecondTime"; - // GIVEN openDJController.assumeStopped(); OperationResult parentResult = createOperationResult(); @@ -1498,7 +1475,6 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception .createModifyDelta(USER_JACKIE_OID, modifications, UserType.class); Task task = taskManager.createTaskInstance(); - XMLGregorianCalendar lastRequestStartTs = clock.currentTimeXMLGregorianCalendar(); executeChanges(objectDelta, null, task, parentResult); XMLGregorianCalendar lastRequestEndTs = clock.currentTimeXMLGregorianCalendar(); @@ -1514,7 +1490,7 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception String shadowOid = getLinkRefOid(USER_JACKIE_OID, RESOURCE_OPENDJ_OID); assertModelShadowNoFetch(shadowOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + "Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertNotDead() .assertNoLegacyConsistency() @@ -1578,8 +1554,6 @@ public void test251ModifyFocusCommunicationProblemSecondTime() throws Exception */ @Test public void test260GetDiscoveryAddCommunicationProblem() throws Exception { - final String TEST_NAME = "test260GetDiscoveryAddCommunicationProblem"; - // GIVEN openDJController.assumeStopped(); display("OpenDJ stopped"); @@ -1609,7 +1583,7 @@ public void test260GetDiscoveryAddCommunicationProblem() throws Exception { String shadowOid = getLinkRefOid(USER_ANGELIKA_OID, RESOURCE_OPENDJ_OID); assertRepoShadow(shadowOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + ".Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertIsNotExists() .assertNotDead() @@ -1644,11 +1618,9 @@ public void test260GetDiscoveryAddCommunicationProblem() throws Exception { @Test public void test262GetDiscoveryModifyCommunicationProblem() throws Exception { - final String TEST_NAME = "test262GetDiscoveryModifyCommunicationProblem"; - // GIVEN openDJController.assumeRunning(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult parentResult = task.getResult(); //prepare user @@ -1673,7 +1645,7 @@ public void test262GetDiscoveryModifyCommunicationProblem() throws Exception { XMLGregorianCalendar lastRequestEndTs = clock.currentTimeXMLGregorianCalendar(); assertModelShadowNoFetch(shadowOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + "Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertIsExists() .assertNotDead() @@ -1735,11 +1707,9 @@ public void test262GetDiscoveryModifyCommunicationProblem() throws Exception { @Test public void test264GetDiscoveryModifyUserPasswordCommunicationProblem() throws Exception { - final String TEST_NAME = "test264GetDiscoveryModifyUserPasswordCommunicationProblem"; - // GIVEN openDJController.assumeStopped(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult parentResult = task.getResult(); assertUser(USER_ALICE_OID, "User before") @@ -1754,7 +1724,7 @@ public void test264GetDiscoveryModifyUserPasswordCommunicationProblem() throws E // THEN //check the state after execution assertModelShadowNoFetch(shadowOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + ".Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertIsExists() .assertNotDead() @@ -1796,7 +1766,6 @@ public void test264GetDiscoveryModifyUserPasswordCommunicationProblem() throws E .display() .assertModify() .assertHasModification(createAttributePath(LDAP_ATTRIBUTE_EMPLOYEE_NUMBER)); - ; //start openDJ openDJController.start(); @@ -1825,11 +1794,9 @@ public void test264GetDiscoveryModifyUserPasswordCommunicationProblem() throws E */ @Test public void test265ModifyUserPasswordCommunicationProblemRecon() throws Exception { - final String TEST_NAME = "test265ModifyUserPasswordCommunicationProblemRecon"; - // GIVEN openDJController.assumeStopped(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); assertUser(USER_ALICE_OID, "User before") @@ -1846,7 +1813,7 @@ public void test265ModifyUserPasswordCommunicationProblemRecon() throws Exceptio then(); //check the state after execution assertModelShadowNoFetch(shadowOid) - .display(TEST_NAME + "Shadow after") + .display(getTestNameShort() + ".Shadow after") .assertKind(ShadowKindType.ACCOUNT) .assertIsExists() .assertNotDead() @@ -1899,8 +1866,6 @@ public void test265ModifyUserPasswordCommunicationProblemRecon() throws Exceptio */ @Test public void test270ModifyDiscoveryAddCommunicationProblem() throws Exception { - final String TEST_NAME = "test270ModifyDiscoveryAddCommunicationProblem"; - // GIVEN openDJController.assumeStopped(); OperationResult parentResult = createOperationResult(); @@ -1954,8 +1919,6 @@ public void test270ModifyDiscoveryAddCommunicationProblem() throws Exception { @Test public void test280ModifyObjectCommunicationProblemWeakMapping() throws Exception { - final String TEST_NAME = "test280ModifyObjectCommunicationProblemWeakMapping"; - // GIVEN openDJController.assumeRunning(); OperationResult parentResult = createOperationResult(); @@ -2001,8 +1964,6 @@ public void test280ModifyObjectCommunicationProblemWeakMapping() throws Exceptio @Test public void test282ModifyObjectCommunicationProblemWeakAndStrongMapping() throws Exception { - final String TEST_NAME = "test282ModifyObjectCommunicationProblemWeakAndStrongMapping"; - // GIVEN openDJController.assumeRunning(); OperationResult parentResult = createOperationResult(); @@ -2046,9 +2007,7 @@ public void test282ModifyObjectCommunicationProblemWeakAndStrongMapping() throws .createModificationReplaceProperty(UserType.class, USER_DONALD_OID, UserType.F_GIVEN_NAME, new PolyString("don")); userDelta.addModification(employeeTypeDelta); - XMLGregorianCalendar lastRequestStartTs = clock.currentTimeXMLGregorianCalendar(); executeChanges(userDelta, null, task, parentResult); - XMLGregorianCalendar lastRequestEndTs = clock.currentTimeXMLGregorianCalendar(); assertModelShadowNoFetch(shadowOid) .assertNotDead() @@ -2066,8 +2025,6 @@ public void test282ModifyObjectCommunicationProblemWeakAndStrongMapping() throws @Test public void test283GetObjectNoFetchShadowAndRecompute() throws Exception { - final String TEST_NAME = "test283GetObjectNoFetchShadowAndRecompute"; - // GIVEN openDJController.assumeRunning(); OperationResult parentResult = createOperationResult(); @@ -2105,7 +2062,6 @@ public void test283GetObjectNoFetchShadowAndRecompute() throws Exception { @Test public void test284ModifyObjectAssignToGroupCommunicationProblem() throws Exception { - final String TEST_NAME = "test284ModifyObjectAssignToGroupCommunicationProblem"; Task task = taskManager.createTaskInstance(); OperationResult parentResult = createOperationResult(); // GIVEN @@ -2174,8 +2130,6 @@ public void test284ModifyObjectAssignToGroupCommunicationProblem() throws Except //TODO: enable after notify failure will be implemented.. @Test(enabled = false) public void test400GetDiscoveryAddCommunicationProblemAlreadyExists() throws Exception { - final String TEST_NAME = "test400GetDiscoveryAddCommunicationProblemAlreadyExists"; - // GIVEN openDJController.assumeStopped(); OperationResult parentResult = createOperationResult(); @@ -2219,11 +2173,9 @@ public void test400GetDiscoveryAddCommunicationProblemAlreadyExists() throws Exc */ @Test public void test500AddUserMorganWithAssignment() throws Exception { - final String TEST_NAME = "test500AddUserMorganWithAssignment"; - // GIVEN openDJController.assumeRunning(); - Task task = taskManager.createTaskInstance(TestConsistencyMechanism.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); @@ -2263,11 +2215,9 @@ public void test500AddUserMorganWithAssignment() throws Exception { */ @Test public void test501AddUserChuckWithAssignment() throws Exception { - final String TEST_NAME = "test501AddUserChuckWithAssignment"; - // GIVEN openDJController.assumeRunning(); - Task task = taskManager.createTaskInstance(TestConsistencyMechanism.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); @@ -2319,11 +2269,9 @@ public void test501AddUserChuckWithAssignment() throws Exception { */ @Test public void test502AssignAccountToHerman() throws Exception { - final String TEST_NAME = "test502AssignAccountToHerman"; - // GIVEN openDJController.assumeRunning(); - Task task = taskManager.createTaskInstance(TestConsistencyMechanism.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); @@ -2379,11 +2327,9 @@ public void test502AssignAccountToHerman() throws Exception { */ @Test public void test510UnlinkAndUnassignAccountMorgan() throws Exception { - final String TEST_NAME = "test510UnlinkAndUnassignAccountMorgan"; - // GIVEN openDJController.assumeRunning(); - Task task = taskManager.createTaskInstance(TestConsistencyMechanism.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); @@ -2444,16 +2390,12 @@ public void test510UnlinkAndUnassignAccountMorgan() throws Exception { /** * assign account to the user morgan. Account with the same 'uid' (not dn, nut other secondary identifier already exists) * account should be linked to the user. - * - * @throws Exception */ @Test public void test511AssignAccountMorgan() throws Exception { - final String TEST_NAME = "test511AssignAccountMorgan"; - // GIVEN openDJController.assumeRunning(); - Task task = taskManager.createTaskInstance(TestConsistencyMechanism.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); @@ -2521,10 +2463,8 @@ public void test511AssignAccountMorgan() throws Exception { @Test public void test600DeleteUserAlice() throws Exception { - String TEST_NAME = "test600DeleteUserAlice"; - openDJController.assumeRunning(); - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult parentResult = task.getResult(); ObjectDelta deleteAliceDelta = prismContext.deltaFactory().object() @@ -2544,8 +2484,6 @@ public void test600DeleteUserAlice() throws Exception { @Test public void test601GetDiscoveryModifyCommunicationProblemDirectAccount() throws Exception { - String TEST_NAME = "test601GetDiscoveryModifyCommunicationProblemDirectAccount"; - openDJController.assumeRunning(); OperationResult parentResult = createOperationResult(); @@ -2576,7 +2514,7 @@ public void test601GetDiscoveryModifyCommunicationProblemDirectAccount() throws executeChanges(delta, null, task, parentResult); //check the state after execution - checkPostponedAccountBasic(accountOid, FailedOperationTypeType.MODIFY, true, parentResult); + checkPostponedAccountBasic(accountOid, true, parentResult); //start openDJ openDJController.start(); @@ -2599,11 +2537,9 @@ public void test601GetDiscoveryModifyCommunicationProblemDirectAccount() throws //MID-5844 @Test//(enabled = false) public void test800Reconciliation() throws Exception { - final String TEST_NAME = "test800Reconciliation"; - openDJController.assumeRunning(); - final OperationResult result = new OperationResult(TestConsistencyMechanism.class.getName() + "." + TEST_NAME); + final OperationResult result = createOperationResult(); // TODO: remove this if the previous test is enabled // openDJController.start(); @@ -2692,8 +2628,6 @@ public void test800Reconciliation() throws Exception { //MID-5844 @Test//(enabled = false) public void test801TestReconciliationRename() throws Exception { - final String TEST_NAME = "test801TestReconciliationRename"; - openDJController.assumeRunning(); Task task = getTestTask(); final OperationResult result = task.getResult(); @@ -2835,7 +2769,7 @@ private void checkOpenResourceConfiguration(PrismObject resource, Object rawElement = credentialsPropertyValue.getRawElement(); } - private UserType testAddUserToRepo(String displayMessage, String fileName, String userOid) + private UserType testAddUserToRepo(String fileName) throws IOException, ObjectNotFoundException, SchemaException, EncryptionException, ObjectAlreadyExistsException, ExpressionEvaluationException, CommunicationException, ConfigurationException, PolicyViolationException, SecurityViolationException { @@ -2869,9 +2803,8 @@ private UserType testAddUserToRepo(String displayMessage, String fileName, Strin private String assertUserOneAccountRef(String userOid) throws Exception { OperationResult parentResult = new OperationResult("getObject from repo"); - PrismObject repoUser = repositoryService.getObject(UserType.class, userOid, - null, parentResult); - UserType repoUserType = repoUser.asObjectable(); + PrismObject repoUser = repositoryService.getObject( + UserType.class, userOid, null, parentResult); parentResult.computeStatus(); TestUtil.assertSuccess("getObject has failed", parentResult); @@ -2879,7 +2812,7 @@ private String assertUserOneAccountRef(String userOid) throws Exception { return assertOneAccountRef(repoUser); } - private String assertOneAccountRef(PrismObject user) throws Exception { + private String assertOneAccountRef(PrismObject user) { UserType repoUserType = user.asObjectable(); display("User (repository)", user); @@ -2928,7 +2861,7 @@ private void assertAttributes(ShadowType shadow, String uid, String givenName, S assertAttribute(shadow, "cn", cn); } - private ShadowType checkPostponedAccountBasic(PrismObject failedAccount, FailedOperationTypeType failedOperation, boolean modify, OperationResult parentResult) throws Exception { + private ShadowType checkPostponedAccountBasic(PrismObject failedAccount, boolean modify, OperationResult parentResult) throws Exception { display("Repository shadow (postponed operation expected)", failedAccount); assertNotNull("Shadow must not be null", failedAccount); ShadowType failedAccountType = failedAccount.asObjectable(); @@ -2947,9 +2880,9 @@ private ShadowType checkPostponedAccountBasic(PrismObject failedAcco return failedAccountType; } - private ShadowType checkPostponedAccountBasic(String accountOid, FailedOperationTypeType failedOperation, boolean modify, OperationResult parentResult) throws Exception { + private ShadowType checkPostponedAccountBasic(String accountOid, boolean modify, OperationResult parentResult) throws Exception { PrismObject faieldAccount = repositoryService.getObject(ShadowType.class, accountOid, null, parentResult); - return checkPostponedAccountBasic(faieldAccount, failedOperation, modify, parentResult); + return checkPostponedAccountBasic(faieldAccount, modify, parentResult); } private Collection> createDeltas(Class type, File requestFile, String objectOid) throws IOException, SchemaException, JAXBException { @@ -2964,7 +2897,7 @@ private Collection> createDeltas(Class type, F return deltas; } catch (Exception ex) { - logger.error("ERROR while unmarshalling: {}", ex); + logger.error("ERROR while unmarshalling", ex); throw ex; } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDelayedEnable.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDelayedEnable.java index 298f1898120..5c2ec6becaf 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDelayedEnable.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDelayedEnable.java @@ -6,16 +6,7 @@ */ package com.evolveum.midpoint.testing.story; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; - import java.io.File; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; @@ -41,14 +32,13 @@ /** * Tests for delayed HR enable/disable. - * + *

* HR system has enabled/disabled status. We want to synchronize that status to midPoint, * but we want the information to be delayed by one day. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestDelayedEnable extends AbstractStoryTest { @@ -109,8 +99,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100AddUserMancomb() throws Exception { - final String TEST_NAME = "test100AddUserMancomb"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -139,7 +127,6 @@ public void test100AddUserMancomb() throws Exception { */ @Test public void test102UserMancombTriggerScannerAgain() throws Exception { - final String TEST_NAME = "test102UserMancombTriggerScannerAgain"; displayCurrentTime(); // WHEN @@ -161,8 +148,6 @@ public void test102UserMancombTriggerScannerAgain() throws Exception { */ @Test public void test104UserMancombRecompute() throws Exception { - final String TEST_NAME = "test104UserMancombRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); displayCurrentTime(); @@ -183,20 +168,20 @@ public void test104UserMancombRecompute() throws Exception { private void assertMancombCreated() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D"); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D"); } /** @@ -205,8 +190,6 @@ private void assertMancombCreated() throws Exception { */ @Test public void test110UserMancombRunTriggerScannerDay1() throws Exception { - final String TEST_NAME = "test110UserMancombRunTriggerScannerDay1"; - clockForward("P1D"); // WHEN @@ -228,8 +211,6 @@ public void test110UserMancombRunTriggerScannerDay1() throws Exception { */ @Test public void test112UserMancombRecomputeDay1() throws Exception { - final String TEST_NAME = "test112UserMancombRecomputeDay1"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -251,24 +232,22 @@ public void test112UserMancombRecomputeDay1() throws Exception { private void assertMancombEnabled() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED) .end() - .triggers() + .triggers() .assertNone(); } @Test public void test114UserMancombRunTriggerScannerDay1Again() throws Exception { - final String TEST_NAME = "test114UserMancombRunTriggerScannerDay1Again"; - // WHEN when(); @@ -287,8 +266,6 @@ public void test114UserMancombRunTriggerScannerDay1Again() throws Exception { */ @Test public void test116UserMancombRecomputeDay1Again() throws Exception { - final String TEST_NAME = "test116UserMancombRecomputeDay1Again"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -312,8 +289,6 @@ public void test116UserMancombRecomputeDay1Again() throws Exception { */ @Test public void test120UserMancombHrDisable() throws Exception { - final String TEST_NAME = "test120UserMancombHrDisable"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -337,13 +312,13 @@ public void test120UserMancombHrDisable() throws Exception { private void assertMancombHalfDisabled() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED); } @@ -353,8 +328,6 @@ private void assertMancombHalfDisabled() throws Exception { */ @Test public void test122UserMancombRecompute() throws Exception { - final String TEST_NAME = "test122UserMancombRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -374,8 +347,6 @@ public void test122UserMancombRecompute() throws Exception { @Test public void test124UserMancombDay1TriggerScanner() throws Exception { - final String TEST_NAME = "test124UserMancombDay1TriggerScanner"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -399,8 +370,6 @@ public void test124UserMancombDay1TriggerScanner() throws Exception { */ @Test public void test130UserMancombTriggerScannerDay2() throws Exception { - final String TEST_NAME = "test130UserMancombTriggerScannerDay2"; - clockForward("P1D"); Task task = getTestTask(); @@ -422,13 +391,13 @@ public void test130UserMancombTriggerScannerDay2() throws Exception { private void assertMancombDisabled() throws Exception { assertUserAfter(USER_MANCOMB_OID) - .assertName(USER_MANCOMB_USERNAME) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertName(USER_MANCOMB_USERNAME) + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED); } @@ -439,8 +408,6 @@ private void assertMancombDisabled() throws Exception { */ @Test public void test132UserMancombRecomputeDay2() throws Exception { - final String TEST_NAME = "test132UserMancombRecomputeDay2"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -460,8 +427,6 @@ public void test132UserMancombRecomputeDay2() throws Exception { @Test public void test132UserMancombRecomputeDay2Again() throws Exception { - final String TEST_NAME = "test132UserMancombRecomputeDay2Again"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -485,8 +450,6 @@ public void test132UserMancombRecomputeDay2Again() throws Exception { */ @Test public void test140UserMancombRecomputeDay3() throws Exception { - final String TEST_NAME = "test140UserMancombRecomputeDay3"; - clockForward("P1D"); Task task = getTestTask(); @@ -510,8 +473,6 @@ public void test140UserMancombRecomputeDay3() throws Exception { @Test public void test200HrLivesyncTask() throws Exception { - final String TEST_NAME = "test200HrLivesyncTask"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -521,18 +482,16 @@ public void test200HrLivesyncTask() throws Exception { addObject(TASK_DUMMY_HR_FILE, task, result); // THEN - then(); - assertSuccess(result); + then(); + assertSuccess(result); - waitForTaskStart(TASK_DUMMY_HR_OID, true); + waitForTaskStart(TASK_DUMMY_HR_OID, true); - assertCounterIncrement(InternalCounters.TRIGGER_FIRED_COUNT, 0); + assertCounterIncrement(InternalCounters.TRIGGER_FIRED_COUNT, 0); } @Test public void test210HrAddUserGuybrush() throws Exception { - final String TEST_NAME = "test210HrAddUserGuybrush"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -564,8 +523,6 @@ public void test210HrAddUserGuybrush() throws Exception { @Test public void test212HrUserGuybrushSyncAgain() throws Exception { - final String TEST_NAME = "test212HrUserGuybrushSyncAgain"; - clockForward("PT1H"); Task task = getTestTask(); @@ -587,8 +544,6 @@ public void test212HrUserGuybrushSyncAgain() throws Exception { @Test public void test214HrUserGuybrushRunTriggers() throws Exception { - final String TEST_NAME = "test214HrUserGuybrushRunTriggers"; - clockForward("PT1H"); Task task = getTestTask(); @@ -610,8 +565,6 @@ public void test214HrUserGuybrushRunTriggers() throws Exception { @Test public void test216HrUserGuybrushRecompute() throws Exception { - final String TEST_NAME = "test216HrUserGuybrushRecompute"; - clockForward("PT1H"); Task task = getTestTask(); @@ -633,8 +586,6 @@ public void test216HrUserGuybrushRecompute() throws Exception { @Test public void test218HrUserGuybrushReconcile() throws Exception { - final String TEST_NAME = "test218HrUserGuybrushReconcile"; - clockForward("PT1H"); Task task = getTestTask(); @@ -654,29 +605,27 @@ public void test218HrUserGuybrushReconcile() throws Exception { assertCounterIncrement(InternalCounters.TRIGGER_FIRED_COUNT, 0); } - private UserAsserter assertGuybrushCreated(UserAsserter userAsserter) throws Exception { + private UserAsserter assertGuybrushCreated(UserAsserter userAsserter) { return userAsserter - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D") - .end() + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFutureBetween(hrCreateTsStart, hrCreateTsEnd, "P1D") + .end() .end(); } @Test public void test220HrUserGuybrushDay1() throws Exception { - final String TEST_NAME = "test220HrUserGuybrushDay1"; - clockForward("P1D"); // WHEN @@ -694,8 +643,6 @@ public void test220HrUserGuybrushDay1() throws Exception { @Test public void test222HrUserGuybrushDay1SyncAgain() throws Exception { - final String TEST_NAME = "test222HrUserGuybrushDay1SyncAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -715,8 +662,6 @@ public void test222HrUserGuybrushDay1SyncAgain() throws Exception { @Test public void test224HrUserGuybrushDay1TriggerScanAgain() throws Exception { - final String TEST_NAME = "test224HrUserGuybrushDay1TriggerScanAgain"; - clockForward("PT1H"); Task task = getTestTask(); @@ -738,8 +683,6 @@ public void test224HrUserGuybrushDay1TriggerScanAgain() throws Exception { @Test public void test226HrUserGuybrushDay1Recompute() throws Exception { - final String TEST_NAME = "test226HrUserGuybrushDay1Recompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -759,8 +702,6 @@ public void test226HrUserGuybrushDay1Recompute() throws Exception { @Test public void test228HrUserGuybrushDay1Reconcile() throws Exception { - final String TEST_NAME = "test228HrUserGuybrushDay1Reconcile"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -780,25 +721,23 @@ public void test228HrUserGuybrushDay1Reconcile() throws Exception { private void assertGuybrushEnabled() throws Exception { assertUserAfter(userGuybrushOid) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_ENABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrCreateTsStart, hrCreateTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED) .end() - .triggers() + .triggers() .assertNone(); } @Test public void test230HrDisableGuybrush() throws Exception { - final String TEST_NAME = "test230HrDisableGuybrush"; - getDummyResourceHr() - .getAccountByUsername(ACCOUNT_GUYBRUSH_USERNAME) + .getAccountByUsername(ACCOUNT_GUYBRUSH_USERNAME) .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_TITLE_NAME, EXT_HR_STATUS_DISABLED); hrModifyTsStart = clock.currentTimeXMLGregorianCalendar(); @@ -820,8 +759,6 @@ public void test230HrDisableGuybrush() throws Exception { @Test public void test232GuybrushHrSyncAgain() throws Exception { - final String TEST_NAME = "test232GuybrushHrSyncAgain"; - // WHEN when(); @@ -837,8 +774,6 @@ public void test232GuybrushHrSyncAgain() throws Exception { @Test public void test234GuybrushRecompute() throws Exception { - final String TEST_NAME = "test232GuybrushHrSyncAgain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -858,8 +793,6 @@ public void test234GuybrushRecompute() throws Exception { @Test public void test236GuybrushReconcile() throws Exception { - final String TEST_NAME = "test236GuybrushReconcile"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -879,8 +812,6 @@ public void test236GuybrushReconcile() throws Exception { @Test public void test238GuybrushrunTriggersAgain() throws Exception { - final String TEST_NAME = "test238GuybrushrunTriggersAgain"; - clockForward("PT1H"); // WHEN @@ -898,25 +829,23 @@ public void test238GuybrushrunTriggersAgain() throws Exception { private void assertGuybrushHalfDisabled() throws Exception { assertUserAfter(userGuybrushOid) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.ENABLED) .assertAdministrativeStatus(ActivationStatusType.ENABLED) .end() - .triggers() + .triggers() .single() - .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) - .assertTimestampFutureBetween(hrModifyTsStart, hrModifyTsEnd, "P1D"); + .assertHandlerUri(RecomputeTriggerHandler.HANDLER_URI) + .assertTimestampFutureBetween(hrModifyTsStart, hrModifyTsEnd, "P1D"); } @Test public void test240HrUserGuybrushDay2() throws Exception { - final String TEST_NAME = "test240HrUserGuybrushDay2"; - clockForward("P1D"); // WHEN @@ -934,8 +863,6 @@ public void test240HrUserGuybrushDay2() throws Exception { @Test public void test242GuybrushRecompute() throws Exception { - final String TEST_NAME = "test242GuybrushRecompute"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -955,8 +882,6 @@ public void test242GuybrushRecompute() throws Exception { @Test public void test244GuybrushHrSyncAgain() throws Exception { - final String TEST_NAME = "test244GuybrushHrSyncAgain"; - // WHEN when(); @@ -972,8 +897,6 @@ public void test244GuybrushHrSyncAgain() throws Exception { @Test public void test246GuybrushReconcile() throws Exception { - final String TEST_NAME = "test246GuybrushReconcile"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -993,16 +916,16 @@ public void test246GuybrushReconcile() throws Exception { private void assertGuybrushDisabled() throws Exception { assertUserAfter(userGuybrushOid) - .assertSubtype(SUBTYPE_EMPLOYEE) - .extension() + .assertSubtype(SUBTYPE_EMPLOYEE) + .extension() .assertPropertyValuesEqual(EXT_HR_STATUS_QNAME, EXT_HR_STATUS_DISABLED) .assertTimestampBetween(EXT_HR_STATUS_CHANGE_TIMESTAMP_QNAME, hrModifyTsStart, hrModifyTsEnd) .end() - .activation() + .activation() .assertEffectiveStatus(ActivationStatusType.DISABLED) .assertAdministrativeStatus(ActivationStatusType.DISABLED) .end() - .triggers() + .triggers() .assertNone(); } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java index cf89687ba03..851a47337c9 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java @@ -42,7 +42,6 @@ public class TestDependencyRename extends AbstractStoryTest { protected static final File RESOURCE_DUMMY_PHONEBOOK_FILE = new File(TEST_DIR, "resource-dummy-phonebook.xml"); protected static final String RESOURCE_DUMMY_PHONEBOOK_ID = "phonebook"; protected static final String RESOURCE_DUMMY_PHONEBOOK_OID = "10000000-0000-0000-0000-000000000001"; - protected static final String RESOURCE_DUMMY_PHONEBOOK_NAMESPACE = MidPointConstants.NS_RI; protected static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; @@ -76,7 +75,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -102,8 +101,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_PHONEBOOK_OID, task); TestUtil.assertSuccess(testResultHr); @@ -116,8 +114,7 @@ public void test000Sanity() throws Exception { @Test public void test100AddUserHerman() throws Exception { - final String TEST_NAME = "test100AddUserHerman"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUserDefinition().instantiate(); @@ -146,8 +143,7 @@ public void test100AddUserHerman() throws Exception { @Test public void test110HermanAssignRoleBasic() throws Exception { - final String TEST_NAME = "test110HermanAssignRoleBasic"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java index 63c7327a3f1..fb7bbe5c91b 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapVirtualGroup.java @@ -10,7 +10,6 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; @@ -77,9 +76,6 @@ public class TestLdapVirtualGroup extends AbstractLdapTest { public static final File TEST_DIR = new File(LDAP_TEST_DIR, "virtualgroup"); private static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; - private static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - /// private static final QName OPENDJ_ASSOCIATION_GROUP_NAME = new - /// QName(RESOURCE_OPENDJ_NAMESPACE, "group"); public static final String ORG_TOP_OID = "00000000-8888-6666-0000-100000000001"; @@ -101,20 +97,10 @@ public class TestLdapVirtualGroup extends AbstractLdapTest { private static final String USER_2_NAME = "User2"; private static final String USER_3_NAME = "User3"; - private static String user0Oid; - private static String user1Oid; - private static String user2Oid; - private static String user3Oid; - - private static final String ORG_TYPE_FUNCTIONAL = "functional"; - private static final String LDAP_INTENT_DEFAULT = "default"; private static final String LDAP_INTENT_VIRTUALSTATIC = "virtualstatic"; private static final String LDAP_INTENT_DYNAMIC = "dynamic"; - private ResourceType resourceOpenDjType; - private PrismObject resourceOpenDj; - @Override protected String getLdapResourceOid() { return RESOURCE_OPENDJ_OID; @@ -161,7 +147,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -170,9 +156,8 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); // Resources - resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, + PrismObject resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, initTask, initResult); - resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); // Org @@ -233,8 +218,7 @@ public void test090AddItRoleHR() throws Exception { @Test public void test100AddItDevRole() throws Exception { - final String TEST_NAME = "test100AddItDevRole"; - Task task = taskManager.createTaskInstance(TestLdapVirtualGroup.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject roleBefore = createLdapRole(ROLE_IT_DEV_NAME); @@ -463,23 +447,6 @@ public void test240AssignJobRoleMultiJobToUser3() throws Exception { } - private PrismObject createOrg(String name, String parentOrgOid) throws SchemaException { - PrismObject org = prismContext.getSchemaRegistry() - .findObjectDefinitionByCompileTimeClass(OrgType.class).instantiate(); - OrgType orgType = org.asObjectable(); - orgType.setName(new PolyStringType(name)); - orgType.getOrgType().add(ORG_TYPE_FUNCTIONAL); - if (parentOrgOid != null) { - AssignmentType parentAssignment = new AssignmentType(); - ObjectReferenceType parentAssignmentTargetRef = new ObjectReferenceType(); - parentAssignmentTargetRef.setOid(parentOrgOid); - parentAssignmentTargetRef.setType(OrgType.COMPLEX_TYPE); - parentAssignment.setTargetRef(parentAssignmentTargetRef); - orgType.getAssignment().add(parentAssignment); - } - return org; - } - private PrismObject createLdapRole(String name) throws SchemaException { PrismObject role = prismContext.getSchemaRegistry() .findObjectDefinitionByCompileTimeClass(RoleType.class).instantiate(); @@ -512,7 +479,6 @@ private void assertLdapUserObject(PrismObject user, ShadowKindType kin } Entry objEntry = openDJController.searchSingle(search); assertNotNull("No LDAP entry for " + userName + ", kind " + kind + ", intent " + intent, objEntry); - ; display("LDAP entry kind " + kind + " inten " + intent + " ldapObj", objEntry); } @@ -538,13 +504,13 @@ private void assertLdapObject(PrismObject role, ShadowKindType kind, S } Entry objEntry = openDJController.searchSingle(search); assertNotNull("No LDAP entry for " + roleName + ", kind " + kind + ", intent " + intent, objEntry); - ; display("LDAP entry kind " + kind + " inten " + intent + " ldapObj", objEntry); } - private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, String intent, String attribute, - String... values) throws SchemaException, ObjectNotFoundException, SecurityViolationException, - CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { + private void assertShadowAttribute(PrismObject focus, + ShadowKindType kind, String intent, String attribute, String... values) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, + CommunicationException, ConfigurationException, ExpressionEvaluationException { String focusName = focus.getName().toString(); display("assert focus " + focus.getCompileTimeClass(), focusName); @@ -552,7 +518,7 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin PrismObject objShadow = getShadowModel(objOid); display("Focus " + focusName + " kind " + kind + " intent " + intent + " shadow", objShadow); - List valuesList = new ArrayList(Arrays.asList(values)); + List valuesList = new ArrayList<>(Arrays.asList(values)); for (Object att : objShadow.asObjectable().getAttributes().asPrismContainerValue().getItems()) { if (att instanceof ResourceAttribute) { @@ -560,7 +526,7 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin if (attribute.equals(((ResourceAttribute) att).getNativeAttributeName())) { - List propValsString = new ArrayList(propVals.size()); + List propValsString = new ArrayList<>(propVals.size()); for (Object pval : propVals) { propValsString.add(pval.toString()); } @@ -569,21 +535,11 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin Collections.sort(valuesList); assertEquals(propValsString, valuesList); - } } } } - protected PrismObject getRoleByNameX(String roleName) throws SchemaException, ObjectNotFoundException, - SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - PrismObject role = findObjectByName(RoleType.class, roleName); - assertNotNull("The role " + roleName + " is missing!", role); - display("Role " + roleName, role); - PrismAsserts.assertPropertyValue(role, RoleType.F_NAME, PrismTestUtil.createPolyString(roleName)); - return role; - } - protected PrismObject getObjectByName( Class clazz, String name) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -593,5 +549,4 @@ protected Date: Sun, 8 Mar 2020 23:46:49 +0100 Subject: [PATCH 29/55] AdTestMixin.java: added class javadoc --- .../com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java | 3 +++ 1 file changed, 3 insertions(+) diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java index cda56d91940..514bf27c05c 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java @@ -28,6 +28,9 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; +/** + * Mixin providing common methods/utilities for Active Directory (AD) related tests. + */ public interface AdTestMixin extends MidpointTestMixin { String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; From aa1dbfc266dd13236556e8986c06fc3c104cf8f8 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 00:16:33 +0100 Subject: [PATCH 30/55] MidpointTestMixin now provides also getTestNumber() --- tools/test-ng/pom.xml | 4 ++++ .../tools/testng/MidpointTestMixin.java | 19 +++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/tools/test-ng/pom.xml b/tools/test-ng/pom.xml index e3a842e2bae..2bd435de12a 100644 --- a/tools/test-ng/pom.xml +++ b/tools/test-ng/pom.xml @@ -37,5 +37,9 @@ org.jetbrains annotations + + org.apache.commons + commons-lang3 + diff --git a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java index e3756b522db..2425d4f606c 100644 --- a/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java +++ b/tools/test-ng/src/main/java/com/evolveum/midpoint/tools/testng/MidpointTestMixin.java @@ -8,6 +8,7 @@ import java.util.Objects; +import org.apache.commons.lang3.StringUtils; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.slf4j.Logger; @@ -69,6 +70,24 @@ default String getTestNameLong() { return testContext().getTestNameLong(); } + /** + * Returns the number of the test derived from the method name in form "testXxxDescription". + * Number is returned as a string with all leading zeroes preserved. + * Fails if the method name does not conform to the "testXxx" prefix to prevent invalid usage. + * Also fails if test-method context is not available. + */ + default String getTestNumber() { + String methodName = testContext().getTestMethodName(); + if (methodName.startsWith("test") && methodName.length() >= 7) { + String testNumber = methodName.substring(4, 7); + if (StringUtils.isNumeric(testNumber)) { + return testNumber; + } + } + throw new IllegalArgumentException( + "Test method name doesn't start with \"testXxx\" (Xxx = test number)."); + } + /** * Returns test class logger. */ From e1c933fe15507b38c01688fb734e2c2026124efc Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 00:17:40 +0100 Subject: [PATCH 31/55] POM: removed commons-lang3 declaration, we'll take it from Spring Boot --- pom.xml | 6 ------ 1 file changed, 6 deletions(-) diff --git a/pom.xml b/pom.xml index 4e0e126edb3..cc25cc12407 100644 --- a/pom.xml +++ b/pom.xml @@ -146,7 +146,6 @@ 2.6 2.6 - 3.7 1.2 3.3.1 3.3.0 @@ -567,11 +566,6 @@ commons-lang ${commons.lang.version} - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - commons-pool commons-pool From bc00e559f13965e582347732e9da82689b78072a Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 00:19:56 +0100 Subject: [PATCH 32/55] more test cleanup, TEST_NAME nearly gone, getTestNumber() utilized Also some serious TODOs in TestQuartzTaskManagerContract. Currently TEST_NAME is only in story tests (and TracerImpl, but that will be fixed differently). --- .../impl/association/TestAddAssociation.java | 4 +- .../ucf/impl/connid/AbstractUcfDummyTest.java | 14 +- .../ucf/impl/connid/TestUcfDummy.java | 43 +- .../ucf/impl/connid/TestUcfDummyMulti.java | 17 +- .../ucf/impl/connid/TestUcfOpenDj.java | 41 +- .../quartzimpl/AbstractTaskManagerTest.java | 8 +- .../task/quartzimpl/TestPartitioning.java | 19 +- .../TestQuartzTaskManagerContract.java | 376 ++++++++---------- .../quartzimpl/TestWorkBucketStrategies.java | 85 ++-- .../task/quartzimpl/TestWorkDistribution.java | 196 +++++---- .../quartzimpl/TestWorkersManagement.java | 89 ++--- 11 files changed, 395 insertions(+), 497 deletions(-) diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java index a963dfcfa32..f1e446bdee6 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java @@ -303,9 +303,7 @@ boolean decideOnApproval(CaseType subcase, */ @Test public void test100AddJackToGuests() throws Exception { - final String TEST_NAME = "test100AddJackToGuests"; - - Task modelTask = taskManager.createTaskInstance(TEST_NAME); + Task modelTask = getTestTask(); OperationResult result = createOperationResult(); modelTask.setOwner(repositoryService.getObject(UserType.class, USER_ADMINISTRATOR_OID, null, result)); diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java index 0718fa3317e..183f79d2887 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/AbstractUcfDummyTest.java @@ -7,10 +7,8 @@ package com.evolveum.midpoint.provisioning.ucf.impl.connid; import java.io.File; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.path.ItemName; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.context.ContextConfiguration; import org.testng.annotations.BeforeClass; @@ -19,6 +17,7 @@ import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContext; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.provisioning.ucf.api.ConnectorFactory; @@ -27,9 +26,9 @@ import com.evolveum.midpoint.schema.SchemaConstantsGenerated; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ResourceSchema; -import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.xml.ns._public.common.common_3.ConnectorType; @@ -39,13 +38,14 @@ * Simple UCF tests. No real resource, just basic setup and sanity. * * @author Radovan Semancik - * + *

* This is an UCF test. It shold not need repository or other things from the midPoint spring context * except from the provisioning beans. But due to a general issue with spring context initialization * this is a lesser evil for now (MID-392) */ @ContextConfiguration(locations = { "classpath:ctx-ucf-connid-test.xml" }) -public abstract class AbstractUcfDummyTest extends AbstractSpringTest { +public abstract class AbstractUcfDummyTest extends AbstractSpringTest + implements OperationResultTestMixin { protected static final File RESOURCE_DUMMY_FILE = new File(UcfTestUtil.TEST_DIR, "resource-dummy.xml"); protected static final File CONNECTOR_DUMMY_FILE = new File(UcfTestUtil.TEST_DIR, "connector-dummy.xml"); @@ -85,10 +85,6 @@ public void setup() throws Exception { connectorType = connector.asObjectable(); } - protected OperationResult createResult() { - return new OperationResult(contextName()); - } - protected void assertPropertyDefinition(PrismContainer container, String propName, QName xsdType, int minOccurs, int maxOccurs) { QName propQName = new QName(SchemaConstantsGenerated.NS_COMMON, propName); diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java index 8e373e22e30..b97f1c616e4 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummy.java @@ -122,7 +122,7 @@ public void test002ConnectorSchema() throws Exception { */ @Test public void test010ListConnectors() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); Set connectors = connectorFactory.listConnectors(null, result); System.out.println("---------------------------------------------------------------------"); @@ -149,8 +149,9 @@ public void test020CreateConfiguredConnector() throws Exception { "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - OperationResult result = createResult(); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + OperationResult result = createOperationResult(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); // WHEN @@ -171,7 +172,7 @@ public void test022ConnectorStatsConfigured() throws Exception { assertNotNull("null operational status", operationalStatus); assertEquals("Wrong connectorClassName", DummyConnector.class.getName(), operationalStatus.getConnectorClassName()); - assertEquals("Wrong poolConfigMinSize", null, operationalStatus.getPoolConfigMinSize()); + assertNull("Wrong poolConfigMinSize", operationalStatus.getPoolConfigMinSize()); assertEquals("Wrong poolConfigMaxSize", (Integer) 10, operationalStatus.getPoolConfigMaxSize()); assertEquals("Wrong poolConfigMinIdle", (Integer) 1, operationalStatus.getPoolConfigMinIdle()); assertEquals("Wrong poolConfigMaxIdle", (Integer) 10, operationalStatus.getPoolConfigMaxIdle()); @@ -183,14 +184,15 @@ public void test022ConnectorStatsConfigured() throws Exception { @Test public void test030ResourceSchema() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); cc = connectorFactory.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(resourceType), "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); //ResourceTypeUtil.getSchemaGenerationConstraints(resourceType) cc.configure(configContainer, null, result); @@ -219,14 +221,15 @@ public void test030ResourceSchema() throws Exception { @Test public void test031ResourceSchemaAccountObjectClass() throws Exception { - OperationResult result = createResult(); + OperationResult result = createOperationResult(); cc = connectorFactory.createConnectorInstance(connectorType, ResourceTypeUtil.getResourceNamespace(resourceType), "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); List objectClassesToGenerate = new ArrayList<>(); QName accountObjectClass = new QName(resource.asObjectable().getNamespace(), "AccountObjectClass"); @@ -256,7 +259,7 @@ public void test033ConnectorStatsInitialized() throws Exception { assertNotNull("null operational status", operationalStatus); assertEquals("Wrong connectorClassName", DummyConnector.class.getName(), operationalStatus.getConnectorClassName()); - assertEquals("Wrong poolConfigMinSize", null, operationalStatus.getPoolConfigMinSize()); + assertNull("Wrong poolConfigMinSize", operationalStatus.getPoolConfigMinSize()); assertEquals("Wrong poolConfigMaxSize", (Integer) 10, operationalStatus.getPoolConfigMaxSize()); assertEquals("Wrong poolConfigMinIdle", (Integer) 1, operationalStatus.getPoolConfigMinIdle()); assertEquals("Wrong poolConfigMaxIdle", (Integer) 10, operationalStatus.getPoolConfigMaxIdle()); @@ -268,9 +271,7 @@ public void test033ConnectorStatsInitialized() throws Exception { @Test public void test040AddAccount() throws Exception { - final String TEST_NAME = "test040AddAccount"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition defaultAccountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); ShadowType shadowType = new ShadowType(); @@ -315,7 +316,7 @@ public boolean handle(PrismObject shadow) { } }; - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // WHEN cc.search(accountDefinition, null, handler, null, null, null, null, result); @@ -334,10 +335,9 @@ private void checkUcfShadow(PrismObject shadow, ObjectClassComplexTy @Test public void test100FetchEmptyChanges() throws Exception { - final String TEST_NAME = "test100FetchEmptyChanges"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); - ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); + OperationResult result = createOperationResult(); + ObjectClassComplexTypeDefinition accountDefinition = + resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); // WHEN PrismProperty lastToken = cc.fetchCurrentToken(accountDefinition, null, result); @@ -361,9 +361,7 @@ public void test100FetchEmptyChanges() throws Exception { @Test public void test101FetchAddChange() throws Exception { - final String TEST_NAME = "test101FetchAddChange"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); PrismProperty lastToken = cc.fetchCurrentToken(accountDefinition, null, result); @@ -396,10 +394,8 @@ public void test101FetchAddChange() throws Exception { @Test public void test500SelfTest() { - final String TEST_NAME = "test500SelfTest"; - // GIVEN - OperationResult testResult = new OperationResult(TestUcfDummy.class + "." + TEST_NAME); + OperationResult testResult = createOperationResult(); // WHEN connectorFactoryIcfImpl.selfTest(testResult); @@ -409,5 +405,4 @@ public void test500SelfTest() { IntegrationTestTools.display(testResult); TestUtil.assertSuccess(testResult); } - } diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java index 850f23a3d15..7c555ba8a4f 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfDummyMulti.java @@ -70,8 +70,9 @@ public void test020CreateConfiguredConnector() throws Exception { "dummy", "description of dummy test connector instance"); assertNotNull("Failed to instantiate connector", cc); - OperationResult result = createResult(); - PrismContainerValue configContainer = resourceType.getConnectorConfiguration().asPrismContainerValue(); + OperationResult result = createOperationResult(); + PrismContainerValue configContainer = + resourceType.getConnectorConfiguration().asPrismContainerValue(); display("Configuration container", configContainer); // WHEN @@ -87,9 +88,7 @@ public void test020CreateConfiguredConnector() throws Exception { @Test public void test100AddAccount() throws Exception { - final String TEST_NAME = "test100AddAccount"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition defaultAccountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); ShadowType shadowType = new ShadowType(); @@ -134,7 +133,7 @@ public boolean handle(PrismObject shadow) { } }; - OperationResult result = createResult(); + OperationResult result = createOperationResult(); // WHEN cc.search(accountDefinition, null, handler, null, null, null, null, result); @@ -152,7 +151,7 @@ public boolean handle(PrismObject shadow) { public void test200BlockingSearch() throws Exception { // GIVEN - OperationResult result = createResult(); + OperationResult result = createOperationResult(); final ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); // Determine object class from the schema @@ -222,7 +221,7 @@ public void test210TwoBlockingSearches() throws Exception { final ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findDefaultObjectClassDefinition(ShadowKindType.ACCOUNT); // Determine object class from the schema - OperationResult result1 = createResult(); + OperationResult result1 = createOperationResult(); final List> searchResults1 = new ArrayList<>(); final ShadowResultHandler handler1 = new ShadowResultHandler() { @Override @@ -233,7 +232,7 @@ public boolean handle(PrismObject shadow) { } }; - OperationResult result2 = createResult(); + OperationResult result2 = createOperationResult(); final List> searchResults2 = new ArrayList<>(); final ShadowResultHandler handler2 = new ShadowResultHandler() { @Override diff --git a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java index e4af410ee96..8d90cbe2dae 100644 --- a/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java +++ b/provisioning/ucf-impl-connid/src/test/java/com/evolveum/midpoint/provisioning/ucf/impl/connid/TestUcfOpenDj.java @@ -258,9 +258,7 @@ private Collection> addSampleResourceObject(String name, St @Test public void test100AddDeleteObject() throws Exception { - final String TEST_NAME = "test100AddDeleteObject"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); Collection> identifiers = addSampleResourceObject("john", "John", "Smith"); @@ -292,9 +290,7 @@ public void test100AddDeleteObject() throws Exception { @Test public void test110ChangeModifyObject() throws Exception { - final String TEST_NAME = "test110ChangeModifyObject"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); Collection> identifiers = addSampleResourceObject("john", "John", "Smith"); @@ -336,9 +332,7 @@ public void test110ChangeModifyObject() throws Exception { @Test public void test200FetchChanges() throws Exception { - final String TEST_NAME = "test200FetchChanges"; - - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findObjectClassDefinition(OpenDJController.OBJECT_CLASS_INETORGPERSON_NAME); PrismProperty lastToken = cc.fetchCurrentToken(accountDefinition, null, result); @@ -445,9 +439,8 @@ public void test310TestConnectionNegative() throws Exception { AssertJUnit.assertNotNull(connectorConnectionResult); System.out.println("Test \"connector connection\" result: " + connectorConnectionResult + " (FAILURE EXPECTED)"); - AssertJUnit.assertTrue("Unexpected success of bad connector test", - !connectorConnectionResult.isSuccess()); - AssertJUnit.assertTrue(!result.isSuccess()); + assertFalse("Unexpected success of bad connector test", connectorConnectionResult.isSuccess()); + assertFalse(result.isSuccess()); } /** @@ -481,8 +474,9 @@ public void test400FetchResourceSchema() throws Exception { AssertJUnit.assertFalse("No identifiers for account object class ", accountDefinition .getPrimaryIdentifiers().isEmpty()); - PrismPropertyDefinition uidDefinition = accountDefinition.findAttributeDefinition( - new QName(ResourceTypeUtil.getResourceNamespace(resourceType), OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME)); + PrismPropertyDefinition uidDefinition = accountDefinition.findAttributeDefinition( + new QName(ResourceTypeUtil.getResourceNamespace(resourceType), + OpenDJController.RESOURCE_OPENDJ_PRIMARY_IDENTIFIER_LOCAL_NAME)); AssertJUnit.assertNotNull(uidDefinition); for (Definition def : resourceSchema.getDefinitions()) { @@ -522,13 +516,11 @@ public void test410Capabilities() throws Exception { @Test public void test500FetchObject() throws Exception { - final String TEST_NAME = "test500FetchObject"; - // GIVEN ResourceAttributeContainer resourceObject = createResourceObject( "uid=Teell,ou=People,dc=example,dc=com", "Teell William", "Teell"); - OperationResult addResult = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult addResult = createOperationResult("addObject"); PrismObject shadow = wrapInShadow(ShadowType.class, resourceObject); // Add a testing object @@ -540,7 +532,7 @@ public void test500FetchObject() throws Exception { // Determine object class from the schema ResourceObjectIdentification identification = new ResourceObjectIdentification(accountDefinition, identifiers, null); - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult("fetchObject"); // WHEN PrismObject ro = cc.fetchObject(identification, null, null, result); @@ -556,7 +548,6 @@ public void test500FetchObject() throws Exception { @Test public void test510Search() throws Exception { - final String TEST_NAME = "test510Search"; // GIVEN ObjectClassComplexTypeDefinition accountDefinition = resourceSchema.findObjectClassDefinition(OpenDJController.OBJECT_CLASS_INETORGPERSON_NAME); @@ -570,7 +561,7 @@ public boolean handle(PrismObject object) { } }; - OperationResult result = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult result = createOperationResult(); // WHEN cc.search(accountDefinition, null, handler, null, null, null, null, result); @@ -581,18 +572,13 @@ public boolean handle(PrismObject object) { @Test public void test600CreateAccountWithPassword() throws Exception { - final String TEST_NAME = "test600CreateAccountWithPassword"; // GIVEN ResourceAttributeContainer resourceObject = createResourceObject( "uid=lechuck,ou=people,dc=example,dc=com", "Ghost Pirate LeChuck", "LeChuck"); ProtectedStringType ps = protector.encryptString("t4k30v3rTh3W0rld"); -// PasswordChangeOperation passOp = new PasswordChangeOperation(ps); -// additionalOperations.add(passOp); - - OperationResult addResult = new OperationResult(this.getClass().getName() - + "." + TEST_NAME); + OperationResult addResult = createOperationResult(); PrismObject shadow = wrapInShadow(ShadowType.class, resourceObject); CredentialsType credentials = new CredentialsType(); @@ -620,13 +606,12 @@ public void test600CreateAccountWithPassword() throws Exception { @Test public void test610ChangePassword() throws Exception { - final String TEST_NAME = "test610ChangePassword"; // GIVEN ResourceAttributeContainer resourceObject = createResourceObject( "uid=drake,ou=People,dc=example,dc=com", "Sir Francis Drake", "Drake"); PrismObject shadow = wrapInShadow(ShadowType.class, resourceObject); - OperationResult addResult = new OperationResult(this.getClass().getName() + "." + TEST_NAME); + OperationResult addResult = createOperationResult(); // Add a testing object cc.addObject(shadow, null, addResult); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java index 6176259d5a3..04b7c23d06d 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java @@ -36,6 +36,7 @@ import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.AbstractSpringTest; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.util.DebugDumpable; import com.evolveum.midpoint.util.PrettyPrinter; import com.evolveum.midpoint.util.exception.CommonException; @@ -44,7 +45,8 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -public class AbstractTaskManagerTest extends AbstractSpringTest { +public class AbstractTaskManagerTest extends AbstractSpringTest + implements OperationResultTestMixin { protected static final String CYCLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-task-handler"; protected static final String CYCLE_FINISHING_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-finishing-task-handler"; @@ -83,10 +85,6 @@ public class AbstractTaskManagerTest extends AbstractSpringTest { protected MockParallelTaskHandler parallelTaskHandler; protected MockLongTaskHandler longTaskHandler; - protected static OperationResult createResult(String test) { - return new OperationResult(TestQuartzTaskManagerContract.class.getName() + ".test" + test); - } - protected void initHandlers() { MockCycleTaskHandler cycleHandler = new MockCycleTaskHandler(false); // ordinary recurring task taskManager.registerHandler(CYCLE_TASK_HANDLER_URI, cycleHandler); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java index 0d6b0ec0fa2..5454d5f1cc7 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java @@ -46,16 +46,12 @@ public void initialize() throws Exception { DebugUtil.setPrettyPrintBeansAs(PrismContext.LANG_YAML); } - private static String taskFilename(String testName, String subId) { - return "src/test/resources/partitioning/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/partitioning/task-" + getTestNumber() + "-" + subId + ".xml"; } - private static String taskOid(String testName, String subId) { - return "44444444-2222-2222-8888-" + testNumber(testName) + subId + "00000000"; - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid(String subId) { + return "44444444-2222-2222-8888-" + getTestNumber() + subId + "00000000"; } @Test @@ -66,14 +62,13 @@ public void test000Integrity() { @Test public void test100DurableRecurring() throws Exception { - final String TEST_NAME = "test100DurableRecurring"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "m")); + addObjectFromFile(taskFilename("m")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "m"); + String masterTaskOid = taskOid("m"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java index dceefebe0d5..0654aeff1d2 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java @@ -55,11 +55,7 @@ import com.evolveum.midpoint.util.exception.SystemException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -/** - * @author Radovan Semancik - */ - -@ContextConfiguration(locations = {"classpath:ctx-task-test.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-task-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) public class TestQuartzTaskManagerContract extends AbstractTaskManagerTest { @@ -68,16 +64,20 @@ public class TestQuartzTaskManagerContract extends AbstractTaskManagerTest { private static final String TASK_OWNER2_OID = "c0c010c0-d34d-b33f-f00d-111111111112"; private static final String NS_WHATEVER = "http://myself.me/schemas/whatever"; - private static String taskFilename(String test) { - return "src/test/resources/basic/task-" + test.substring(4) + ".xml"; + private String taskFilename(String fileSuffix) { + return "src/test/resources/basic/task-" + getTestNameShort().substring(4) + fileSuffix + ".xml"; } - private static String taskOid(String test, String subId) { - return "91919191-76e0-59e2-86d6-55665566" + subId + test.substring(4, 7); + private String taskFilename() { + return taskFilename(""); } - private static String taskOid(String test) { - return taskOid(test, "0"); + private String taskOid(String subId) { + return "91919191-76e0-59e2-86d6-55665566" + subId + getTestNumber(); + } + + private String taskOid() { + return taskOid("0"); } @BeforeSuite @@ -108,22 +108,19 @@ public void test000Integrity() { @Test public void test003GetProgress() throws Exception { - String TEST_NAME = "test003GetProgress"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); logger.trace("Retrieving the task and getting its progress..."); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); AssertJUnit.assertEquals("Progress is not 0", 0, task.getProgress()); } - - @Test(enabled=false) // this is probably OK to fail, so do not enable it (at least for now) + @Test(enabled = false) // this is probably OK to fail, so do not enable it (at least for now) public void test004aTaskBigProperty() throws Exception { - String TEST_NAME = "test004aTaskBigProperty"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); String string300 = "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-" @@ -138,13 +135,14 @@ public void test004aTaskBigProperty() throws Exception { + "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-"; - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); // property definition ItemName bigStringQName = new ItemName("http://midpoint.evolveum.com/repo/test", "bigString"); - MutablePrismPropertyDefinition bigStringDefinition = prismContext.definitionFactory().createPropertyDefinition(bigStringQName, DOMUtil.XSD_STRING); + MutablePrismPropertyDefinition bigStringDefinition = prismContext.definitionFactory() + .createPropertyDefinition(bigStringQName, DOMUtil.XSD_STRING); bigStringDefinition.setIndexed(false); bigStringDefinition.setMinOccurs(0); bigStringDefinition.setMaxOccurs(1); @@ -160,7 +158,7 @@ public void test004aTaskBigProperty() throws Exception { logger.trace("Retrieving the task and comparing its properties..."); - Task task001 = getTask(taskOid(TEST_NAME), result); + Task task001 = getTask(taskOid(), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); PrismProperty bigString001 = task001.getExtensionPropertyOrClone(bigStringQName); @@ -177,7 +175,7 @@ public void test004aTaskBigProperty() throws Exception { System.out.println("2nd round: Task before save = " + task001.debugDump()); task001.flushPendingModifications(result); // however, this does not work, because 'modifyObject' in repo first reads object, overwriting any existing definitions ... - Task task002 = getTask(taskOid(TEST_NAME), result); + Task task002 = getTask(taskOid(), result); System.out.println("2nd round: Task from repo: " + task002.debugDump()); PrismProperty bigString002 = task002.getExtensionPropertyOrClone(bigStringQName); @@ -186,8 +184,7 @@ public void test004aTaskBigProperty() throws Exception { @Test public void test004bTaskBigProperty() throws Exception { - String TEST_NAME = "test004aTaskBigProperty"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); String string300 = "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-" @@ -202,13 +199,15 @@ public void test004bTaskBigProperty() throws Exception { + "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-"; - addObjectFromFile(taskFilename(TEST_NAME)); + // TODO inttest: TEST_NAME was set to "test004aTaskBigProperty"; WHY a and not b? it fails with B now. + // TODO fix B file or what, so we can have this here: addObjectFromFile(taskFilename()); + addObjectFromFile("src/test/resources/basic/task-004aTaskBigProperty.xml"); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); // property definition ItemName shipStateQName = new ItemName("http://myself.me/schemas/whatever", "shipState"); - PrismPropertyDefinition shipStateDefinition = prismContext.getSchemaRegistry().findPropertyDefinitionByElementName(shipStateQName); + PrismPropertyDefinition shipStateDefinition = prismContext.getSchemaRegistry().findPropertyDefinitionByElementName(shipStateQName); assertNotNull("Cannot find property definition for shipState", shipStateDefinition); PrismProperty shipStateProperty = (PrismProperty) shipStateDefinition.instantiate(); @@ -221,7 +220,7 @@ public void test004bTaskBigProperty() throws Exception { logger.trace("Retrieving the task and comparing its properties..."); - Task task001 = getTask(taskOid(TEST_NAME), result); + Task task001 = getTask(taskOid(), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); PrismProperty shipState001 = task001.getExtensionPropertyOrClone(shipStateQName); @@ -235,7 +234,7 @@ public void test004bTaskBigProperty() throws Exception { System.out.println("2nd round: Task before save = " + task001.debugDump()); task001.flushPendingModifications(result); - Task task002 = getTask(taskOid(TEST_NAME), result); + Task task002 = getTask(taskOid(), result); System.out.println("2nd round: Task from repo: " + task002.debugDump()); PrismProperty bigString002 = task002.getExtensionPropertyOrClone(shipStateQName); @@ -244,11 +243,10 @@ public void test004bTaskBigProperty() throws Exception { @Test(enabled = false) public void test004cReferenceInExtension() throws Exception { // ok to fail - String TEST_NAME = "test004cReferenceInExtension"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); System.out.println("Task extension = " + task.getExtensionOrClone()); @@ -266,16 +264,15 @@ public void test004cReferenceInExtension() throws Exception { // o @Test(enabled = false) public void test004TaskProperties() throws Exception { - String TEST_NAME = "test004TaskProperties"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); System.out.println("Task extension = " + task.getExtensionOrClone()); - PrismPropertyDefinition delayDefinition = prismContext.definitionFactory().createPropertyDefinition(SchemaConstants.NOOP_DELAY_QNAME, DOMUtil.XSD_INT); + PrismPropertyDefinition delayDefinition = prismContext.definitionFactory().createPropertyDefinition(SchemaConstants.NOOP_DELAY_QNAME, DOMUtil.XSD_INT); System.out.println("property definition = " + delayDefinition); PrismProperty property = (PrismProperty) delayDefinition.instantiate(); @@ -285,7 +282,7 @@ public void test004TaskProperties() throws Exception { //delta.addV(property.getValues()); delta.setValuesToReplace(PrismValueCollectionsUtil.cloneCollection(property.getValues())); - Collection> modifications = new ArrayList<>(1); + Collection> modifications = new ArrayList<>(1); modifications.add(delta); // TODO fix this code @@ -341,10 +338,6 @@ public void test004TaskProperties() throws Exception { task.setResult(result); - //PrismObject requestee = task.getOwner(); - //task.setRequesteeRef(requestee); does not work - //task.setRequesteeOid(requestee.getOid()); - ObjectReferenceType objectReferenceType = new ObjectReferenceType(); objectReferenceType.setType(UserType.COMPLEX_TYPE); String objectOid = "some-oid..."; @@ -357,12 +350,12 @@ public void test004TaskProperties() throws Exception { logger.trace("Retrieving the task (second time) and comparing its properties..."); - Task task001 = getTask(taskOid(TEST_NAME), result); + Task task001 = getTask(taskOid(), result); logger.trace("Task from repo: " + task001.debugDump()); AssertJUnit.assertEquals(TaskBinding.LOOSE, task001.getBinding()); PrismAsserts.assertEqualsPolyString("Name not", newname, task001.getName()); // AssertJUnit.assertEquals(newname, task001.getName()); - AssertJUnit.assertTrue(10 == task001.getProgress()); + assertEquals(task001.getProgress(), 10); AssertJUnit.assertNotNull(task001.getLastRunStartTimestamp()); AssertJUnit.assertEquals("Start time is not correct", (Long) (currentTime / 1000L), (Long) (task001.getLastRunStartTimestamp() / 1000L)); // e.g. MySQL cuts off millisecond information AssertJUnit.assertNotNull(task001.getLastRunFinishTimestamp()); @@ -431,37 +424,36 @@ public void test004TaskProperties() throws Exception { @Test public void test005Single() throws Exception { - final String TEST_NAME = "test005Single"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on the handler singleHandler1.resetHasRun(); // Add single task. This will get picked by task scanner and executed - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); logger.trace("Retrieving the task..."); - TaskQuartzImpl task = getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = getTask(taskOid(), result); - AssertJUnit.assertNotNull(task); - logger.trace("Task retrieval OK."); + AssertJUnit.assertNotNull(task); + logger.trace("Task retrieval OK."); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task - waitForTaskClose(taskOid(TEST_NAME), result, 10000, 1000); + waitForTaskClose(taskOid(), result, 10000, 1000); logger.info("... done"); // Check task status - Task task1 = getTask(taskOid(TEST_NAME), result); + Task task1 = getTask(taskOid(), result); AssertJUnit.assertNotNull(task1); System.out.println("getTask returned: " + task1.debugDump()); - PrismObject po = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject po = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println("getObject returned: " + po.debugDump()); // .. it should be closed @@ -508,11 +500,10 @@ public void test005Single() throws Exception { @Test public void test006Cycle() throws Exception { - final String TEST_NAME = "test006Cycle"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // But before that check sanity ... a known problem with xsi:type - PrismObject object = addObjectFromFile(taskFilename(TEST_NAME)); + PrismObject object = addObjectFromFile(taskFilename()); ObjectType objectType = object.asObjectable(); TaskType addedTask = (TaskType) objectType; @@ -534,16 +525,16 @@ public void test006Cycle() throws Exception { // We need to wait for a sync interval, so the task scanner has a chance // to pick up this // task - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject t = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject t = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(t.debugDump()); // .. it should be running @@ -589,26 +580,25 @@ private void assertSuccessOrInProgress(Task task) { @Test public void test008MoreHandlers() throws Exception { - final String TEST_NAME = "test008MoreHandlers"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on handlers singleHandler1.resetHasRun(); singleHandler2.resetHasRun(); singleHandler3.resetHasRun(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskClose(taskOid(TEST_NAME), result, 15000, 2000); + waitForTaskClose(taskOid(), result, 15000, 2000); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject o = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject o = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(ObjectTypeUtil.dump(o.getValue().getValue())); // .. it should be closed @@ -645,24 +635,23 @@ public void test008MoreHandlers() throws Exception { @Test public void test009CycleLoose() throws Exception { - final String TEST_NAME = "test009CycleLoose"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this task - waitForTaskProgress(taskOid(TEST_NAME), result, 15000, 2000, 1); + waitForTaskProgress(taskOid(), result, 15000, 2000, 1); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject t = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject t = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(t.debugDump()); // .. it should be running @@ -690,21 +679,20 @@ public void test009CycleLoose() throws Exception { @Test public void test010CycleCronLoose() throws Exception { - final String TEST_NAME = "test010CycleCronLoose"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskProgress(taskOid(TEST_NAME), result, 15000, 2000, 2); + waitForTaskProgress(taskOid(), result, 15000, 2000, 2); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - TaskType t = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result).getValue().getValue(); + TaskType t = repositoryService.getObject(TaskType.class, taskOid(), null, result).getValue().getValue(); System.out.println(ObjectTypeUtil.dump(t)); AssertJUnit.assertEquals(TaskExecutionStatus.RUNNABLE, task.getExecutionStatus()); @@ -728,26 +716,25 @@ public void test010CycleCronLoose() throws Exception { @Test public void test011MoreHandlersAndSchedules() throws Exception { - final String TEST_NAME = "test011MoreHandlersAndSchedules"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on handlers l1Handler.resetHasRun(); l2Handler.resetHasRun(); l3Handler.resetHasRun(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskClose(taskOid(TEST_NAME), result, 30000, 2000); + waitForTaskClose(taskOid(), result, 30000, 2000); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject o = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject o = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(ObjectTypeUtil.dump(o.getValue().getValue())); // .. it should be closed @@ -791,27 +778,26 @@ public void test011MoreHandlersAndSchedules() throws Exception { } /* - * Suspends a running task. - */ + * Suspends a running task. + */ @Test public void test012Suspend() throws Exception { - final String TEST_NAME = "test012Suspend"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); // check if we can read the extension (xsi:type issue) - Task taskTemp = getTask(taskOid(TEST_NAME), result); - PrismProperty delay = taskTemp.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); + Task taskTemp = getTask(taskOid(), result); + PrismProperty delay = taskTemp.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); AssertJUnit.assertEquals("Delay was not read correctly", 2000, delay.getRealValue()); - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); // Check task status (task is running 5 iterations where each takes 2000 ms) - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -842,24 +828,23 @@ public void test012Suspend() throws Exception { @Test public void test013ReleaseAndSuspendLooselyBound() throws Exception { - final String TEST_NAME = "test013ReleaseAndSuspendLooselyBound"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); // check if we can read the extension (xsi:type issue) - PrismProperty delay = task.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); + PrismProperty delay = task.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); AssertJUnit.assertEquals("Delay was not read correctly", 1000, delay.getRealValue()); // let us resume (i.e. start the task) taskManager.resumeTask(task, result); // task is executing for 1000 ms, so we need to wait slightly longer, in order for the execution to be done - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); task.refresh(result); @@ -899,15 +884,14 @@ public void test013ReleaseAndSuspendLooselyBound() throws Exception { @Test public void test014SuspendLongRunning() throws Exception { - final String TEST_NAME = "test014SuspendLongRunning"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); - waitForTaskStart(taskOid(TEST_NAME), result, 10000, 2000); + waitForTaskStart(taskOid(), result, 10000, 2000); task.refresh(result); @@ -958,11 +942,10 @@ public void test014SuspendLongRunning() throws Exception { @Test public void test015DeleteTaskFromRepo() throws Exception { - final String TEST_NAME = "test015DeleteTaskFromRepo"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); - String oid = taskOid(TEST_NAME); + addObjectFromFile(taskFilename()); + String oid = taskOid(); // is the task in Quartz? @@ -971,7 +954,7 @@ public void test015DeleteTaskFromRepo() throws Exception { // Remove task from repo - repositoryService.deleteObject(TaskType.class, taskOid(TEST_NAME), result); + repositoryService.deleteObject(TaskType.class, taskOid(), result); // We need to wait for a sync interval, so the task scanner has a chance // to pick up this task @@ -994,15 +977,14 @@ public void timeout() { @Test public void test016WaitForSubtasks() throws Exception { - final String TEST_NAME = "test016WaitForSubtasks"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); //taskManager.getClusterManager().startClusterManagerThread(); try { - Task rootTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME)), result); - Task firstChildTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME + "-child-1")), result); + Task rootTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename()), result); + Task firstChildTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename("-child-1")), result); Task firstReloaded = taskManager.getTaskByIdentifier(firstChildTask.getTaskIdentifier(), result); assertEquals("Didn't get correct task by identifier", firstChildTask.getOid(), firstReloaded.getOid()); @@ -1014,7 +996,8 @@ public void test016WaitForSubtasks() throws Exception { secondChildTask.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); // will resume it after root starts waiting for tasks taskManager.switchToBackground(secondChildTask, result); - Task firstPrerequisiteTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME + "-prerequisite-1")), result); + Task firstPrerequisiteTask = taskManager.createTaskInstance( + addObjectFromFile(taskFilename("-prerequisite-1")), result); List prerequisities = rootTask.listPrerequisiteTasks(result); assertEquals("Wrong # of prerequisite tasks", 1, prerequisities.size()); @@ -1055,7 +1038,7 @@ public void test016WaitForSubtasks() throws Exception { taskManager.resumeTask(secondChildTask, result); taskManager.resumeTask(secondPrerequisiteTask, result); - final String rootOid = taskOid(TEST_NAME); + final String rootOid = taskOid(); waitForTaskClose(rootOid, result, 60000, 3000); @@ -1076,15 +1059,15 @@ public void test016WaitForSubtasks() throws Exception { @Test public void test017WaitForSubtasksEmpty() throws Exception { - final String TEST_NAME = "test017WaitForSubtasksEmpty"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.getClusterManager().startClusterManagerThread(); try { - Task rootTask = taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME)), result); + Task rootTask = taskManager.createTaskInstance( + addObjectFromFile(taskFilename()), result); display("root task", rootTask); - waitForTaskClose(taskOid(TEST_NAME), result, 40000, 3000); + waitForTaskClose(taskOid(), result, 40000, 3000); } finally { taskManager.getClusterManager().stopClusterManagerThread(10000L, result); } @@ -1092,8 +1075,7 @@ public void test017WaitForSubtasksEmpty() throws Exception { @Test public void test018TaskResult() throws Exception { - final String TEST_NAME = "test018RefreshingResult"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); Task task = taskManager.createTaskInstance(); task.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); @@ -1119,24 +1101,23 @@ public void test018TaskResult() throws Exception { @Test public void test019FinishedHandler() throws Exception { - final String TEST_NAME = "test019FinishedHandler"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); // reset 'has run' flag on handlers singleHandler1.resetHasRun(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - waitForTaskClose(taskOid(TEST_NAME), result, 15000, 2000); + waitForTaskClose(taskOid(), result, 15000, 2000); // Check task status - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); - PrismObject o = repositoryService.getObject(TaskType.class, taskOid(TEST_NAME), null, result); + PrismObject o = repositoryService.getObject(TaskType.class, taskOid(), null, result); System.out.println(ObjectTypeUtil.dump(o.getValue().getValue())); // .. it should be closed @@ -1168,10 +1149,9 @@ public void test019FinishedHandler() throws Exception { @Test public void test020QueryByExecutionStatus() throws Exception { - final String TEST_NAME = "test020QueryByExecutionStatus"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - taskManager.createTaskInstance((PrismObject) (PrismObject) addObjectFromFile(taskFilename(TEST_NAME)), result); + taskManager.createTaskInstance(addObjectFromFile(taskFilename()), result); ObjectFilter filter1 = prismContext.queryFor(TaskType.class).item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.WAITING).buildFilter(); ObjectFilter filter2 = prismContext.queryFor(TaskType.class).item(TaskType.F_WAITING_REASON).eq(TaskWaitingReasonType.OTHER).buildFilter(); @@ -1188,12 +1168,11 @@ public void test020QueryByExecutionStatus() throws Exception { @Test public void test021DeleteTaskTree() throws Exception { - final String TEST_NAME = "test021DeleteTaskTree"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - PrismObject parentTaskPrism = addObjectFromFile(taskFilename(TEST_NAME)); - PrismObject childTask1Prism = addObjectFromFile(taskFilename(TEST_NAME+"-child1")); - PrismObject childTask2Prism = addObjectFromFile(taskFilename(TEST_NAME+"-child2")); + PrismObject parentTaskPrism = addObjectFromFile(taskFilename()); + PrismObject childTask1Prism = addObjectFromFile(taskFilename("-child1")); + PrismObject childTask2Prism = addObjectFromFile(taskFilename("-child2")); AssertJUnit.assertEquals(TaskExecutionStatusType.WAITING, parentTaskPrism.asObjectable().getExecutionStatus()); AssertJUnit.assertEquals(TaskExecutionStatusType.SUSPENDED, childTask1Prism.asObjectable().getExecutionStatus()); @@ -1220,35 +1199,33 @@ public void test021DeleteTaskTree() throws Exception { try { repositoryService.getObject(TaskType.class, childTask1.getOid(), null, result); - assertTrue("Task " + childTask1 + " was not deleted from the repository", false); + fail("Task " + childTask1 + " was not deleted from the repository"); } catch (ObjectNotFoundException e) { // ok! } try { repositoryService.getObject(TaskType.class, childTask2.getOid(), null, result); - assertTrue("Task " + childTask2 + " was not deleted from the repository", false); + fail("Task " + childTask2 + " was not deleted from the repository"); } catch (ObjectNotFoundException e) { // ok! } try { repositoryService.getObject(TaskType.class, parentTask.getOid(), null, result); - assertTrue("Task " + parentTask + " was not deleted from the repository", false); + fail("Task " + parentTask + " was not deleted from the repository"); } catch (ObjectNotFoundException e) { // ok! } - } @Test public void test022ExecuteRecurringOnDemand() throws Exception { - final String TEST_NAME = "test022ExecuteRecurringOnDemand"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); System.out.println("Waiting to see if the task would not start..."); @@ -1266,7 +1243,7 @@ public void test022ExecuteRecurringOnDemand() throws Exception { taskManager.scheduleRunnableTaskNow(task, result); // task is executing for 1000 ms, so we need to wait slightly longer, in order for the execution to be done - waitForTaskProgress(taskOid(TEST_NAME), result, 10000, 2000, 1); + waitForTaskProgress(taskOid(), result, 10000, 2000, 1); task.refresh(result); System.out.println("After refresh: " + task.debugDump()); @@ -1288,12 +1265,11 @@ public void test022ExecuteRecurringOnDemand() throws Exception { @Test public void test100LightweightSubtasks() throws Exception { - final String TEST_NAME = "test100LightweightSubtasks"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - String taskOid = taskOid(TEST_NAME); + String taskOid = taskOid(); Task task = getTask(taskOid, result); System.out.println("After setup: " + task.debugDump()); @@ -1324,7 +1300,7 @@ private void checkTaskStateRepeatedly(String taskOid, OperationResult result, in OperationStatsType stats = task.getOperationStats(); Integer totalSuccessCount = stats != null && stats.getIterativeTaskInformation() != null ? stats.getIterativeTaskInformation().getTotalSuccessCount() : null; - System.out.println((System.currentTimeMillis()-start) + ": subtasks: " + task.getSubtaskRef().size() + + System.out.println((System.currentTimeMillis() - start) + ": subtasks: " + task.getSubtaskRef().size() + ", progress = " + task.getProgress() + ", objects = " + totalSuccessCount); if (task.getExecutionStatus() != TaskExecutionStatusType.RUNNABLE) { System.out.println("Done. Status = " + task.getExecutionStatus()); @@ -1336,15 +1312,14 @@ private void checkTaskStateRepeatedly(String taskOid, OperationResult result, in @Test public void test105LightweightSubtasksSuspension() throws Exception { - final String TEST_NAME = "test105LightweightSubtasksSuspension"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename(TEST_NAME)); + addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(TEST_NAME), result); + Task task = getTask(taskOid(), result); System.out.println("After setup: " + task.debugDump()); - waitForTaskStart(taskOid(TEST_NAME), result, 15000, 500); + waitForTaskStart(taskOid(), result, 15000, 500); task.refresh(result); System.out.println("After refresh (task was started; and it should run now): " + task.debugDump()); @@ -1385,14 +1360,13 @@ public void test105LightweightSubtasksSuspension() throws Exception { @Test public void test108SecondaryGroupLimit() throws Exception { - final String TEST_NAME = "test108SecondaryGroupLimit"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - TaskType task1 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task1 = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); waitForTaskStart(task1.getOid(), result, 10000, 500); // import second task with the same group (expensive) - TaskType task2 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME + "-2")).asObjectable(); + TaskType task2 = (TaskType) addObjectFromFile(taskFilename("-2")).asObjectable(); Thread.sleep(10000); task1 = getTaskType(task1.getOid(), result); @@ -1410,7 +1384,7 @@ public void test108SecondaryGroupLimit() throws Exception { waitForTaskStart(task2Oid, result, 10000, 500); // import third task that has another collision (large-ram) with the second one - TaskType task3 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME + "-3")).asObjectable(); + TaskType task3 = (TaskType) addObjectFromFile(taskFilename("-3")).asObjectable(); Thread.sleep(10000); task2 = getTaskType(task2Oid, result); @@ -1444,16 +1418,15 @@ protected void assertNextRetryTimeSet(TaskType task, OperationResult result) @Test public void test110GroupLimit() throws Exception { - final String TEST_NAME = "test110GroupLimit"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.getExecutionManager().setLocalExecutionLimitations((TaskExecutionLimitationsType) null); - TaskType task1 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task1 = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); waitForTaskStart(task1.getOid(), result, 10000, 500); // import second task with the same group - TaskType task2 = (TaskType) addObjectFromFile(taskFilename(TEST_NAME + "-2")).asObjectable(); + TaskType task2 = (TaskType) addObjectFromFile(taskFilename("-2")).asObjectable(); Thread.sleep(10000); task1 = getTaskType(task1.getOid(), result); @@ -1483,8 +1456,7 @@ private TaskType getTaskType(String oid, OperationResult result) throws SchemaEx @Test public void test120NodeAllowed() throws Exception { - final String TEST_NAME = "test120NodeAllowed"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); taskManager.getExecutionManager().setLocalExecutionLimitations( new TaskExecutionLimitationsType() @@ -1492,7 +1464,7 @@ public void test120NodeAllowed() throws Exception { .groupLimitation(new TaskGroupExecutionLimitationType().groupName(null)) .groupLimitation(new TaskGroupExecutionLimitationType().groupName(TaskConstants.LIMIT_FOR_OTHER_GROUPS).limit(0))); - TaskType task = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); waitForTaskStart(task.getOid(), result, 10000, 500); task = getTaskType(task.getOid(), result); assertNotNull("Task was not started even if it should be", task.getLastRunStartTimestamp()); @@ -1500,10 +1472,9 @@ public void test120NodeAllowed() throws Exception { @Test public void test130NodeNotAllowed() throws Exception { - final String TEST_NAME = "test130NodeNotAllowed"; - final OperationResult result = createResult(TEST_NAME); + final OperationResult result = createOperationResult(); - TaskType task = (TaskType) addObjectFromFile(taskFilename(TEST_NAME)).asObjectable(); + TaskType task = (TaskType) addObjectFromFile(taskFilename()).asObjectable(); Thread.sleep(10000); task = getTaskType(task.getOid(), result); assertNull("Task was started even if it shouldn't be", task.getLastRunStartTimestamp()); @@ -1512,36 +1483,35 @@ public void test130NodeNotAllowed() throws Exception { @Test public void test999CheckingLeftovers() throws Exception { - String TEST_NAME = "test999CheckingLeftovers"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); ArrayList leftovers = new ArrayList<>(); - checkLeftover(leftovers, "test005", result); - checkLeftover(leftovers, "test006", result); - checkLeftover(leftovers, "test008", result); - checkLeftover(leftovers, "test009", result); - checkLeftover(leftovers, "test010", result); - checkLeftover(leftovers, "test011", result); - checkLeftover(leftovers, "test012", result); - checkLeftover(leftovers, "test013", result); - checkLeftover(leftovers, "test014", result); - checkLeftover(leftovers, "test015", result); - checkLeftover(leftovers, "test016", result); - checkLeftover(leftovers, "test017", result); - checkLeftover(leftovers, "test019", result); - checkLeftover(leftovers, "test021", result); - checkLeftover(leftovers, "test021", "1", result); - checkLeftover(leftovers, "test021", "2", result); - checkLeftover(leftovers, "test022", result); - checkLeftover(leftovers, "test100", result); - checkLeftover(leftovers, "test105", result); - checkLeftover(leftovers, "test108", result); - checkLeftover(leftovers, "test108", "a", result); - checkLeftover(leftovers, "test108", "b", result); - checkLeftover(leftovers, "test110", result); - checkLeftover(leftovers, "test110", "a", result); - checkLeftover(leftovers, "test120", result); - checkLeftover(leftovers, "test130", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, "1", result); + checkLeftover(leftovers, "2", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, "a", result); + checkLeftover(leftovers, "b", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, "a", result); + checkLeftover(leftovers, result); + checkLeftover(leftovers, result); StringBuilder message = new StringBuilder("Leftover task(s) found:"); for (String leftover : leftovers) { @@ -1551,12 +1521,12 @@ public void test999CheckingLeftovers() throws Exception { AssertJUnit.assertTrue(message.toString(), leftovers.isEmpty()); } - private void checkLeftover(ArrayList leftovers, String testNumber, OperationResult result) throws Exception { - checkLeftover(leftovers, testNumber, "0", result); + private void checkLeftover(ArrayList leftovers, OperationResult result) throws Exception { + checkLeftover(leftovers, "0", result); } - private void checkLeftover(ArrayList leftovers, String testNumber, String subId, OperationResult result) throws Exception { - String oid = taskOid(testNumber, subId); + private void checkLeftover(ArrayList leftovers, String subId, OperationResult result) throws Exception { + String oid = taskOid(subId); Task t; try { t = getTask(oid, result); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java index 446e9ca3d10..655eddb9907 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java @@ -48,48 +48,44 @@ public class TestWorkBucketStrategies extends AbstractTaskManagerTest { @Autowired private WorkStateManager workStateManager; @Autowired private WorkSegmentationStrategyFactory strategyFactory; - private static String taskFilename(String testName, String subId) { - return "src/test/resources/work-buckets/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/work-buckets/task-" + getTestNumber() + "-" + subId + ".xml"; } - private static String taskFilename(String testName) { - return taskFilename(testName, "0"); + private String taskFilename() { + return taskFilename("0"); } - private static String taskOid(String testName, String subId) { - return "44444444-0000-0000-0000-" + testNumber(testName) + subId + "00000000"; + private String taskOid(String subId) { + return "44444444-0000-0000-0000-" + getTestNumber() + subId + "00000000"; } - private static String taskOid(String test) { - return taskOid(test, "0"); - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid() { + return taskOid("0"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "w"); + protected String workerTaskFilename() { + return taskFilename("w"); } @SuppressWarnings("unused") @NotNull - protected String coordinatorTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "c"); + protected String coordinatorTaskFilename() { + return taskFilename("c"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "w"); + protected String workerTaskOid() { + return taskOid("w"); } @SuppressWarnings("unused") @NotNull - protected String coordinatorTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "c"); + protected String coordinatorTaskOid() { + return taskOid("c"); } @PostConstruct @@ -107,11 +103,10 @@ public void test000Integrity() { @Test public void test100NumericExplicitBuckets() throws Exception { - final String TEST_NAME = "test100NumericExplicitBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkBucketType bucket = workStateManager.getWorkBucket(task.getOid(), 0, null, null, result); @@ -188,11 +183,10 @@ public void test100NumericExplicitBuckets() throws Exception { @Test public void test110FilterExplicitBuckets() throws Exception { - final String TEST_NAME = "test110FilterExplicitBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -276,11 +270,10 @@ public void test110FilterExplicitBuckets() throws Exception { @Test public void test120StringPrefixBuckets() throws Exception { - final String TEST_NAME = "test120StringPrefixBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -332,11 +325,10 @@ public void test120StringPrefixBuckets() throws Exception { @Test public void test125StringExactValueBuckets() throws Exception { - final String TEST_NAME = "test125StringExactValueBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -388,11 +380,10 @@ public void test125StringExactValueBuckets() throws Exception { @Test public void test130StringIntervalBuckets() throws Exception { - final String TEST_NAME = "test130StringIntervalBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -438,11 +429,10 @@ public void test130StringIntervalBuckets() throws Exception { @Test public void test140OidBuckets() throws Exception { - final String TEST_NAME = "test140OidBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -457,11 +447,10 @@ public void test140OidBuckets() throws Exception { @Test public void test150OidBucketsTwice() throws Exception { - final String TEST_NAME = "test150OidBucketsTwice"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java index 85ecd80bf57..d9e3fcc6956 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java @@ -59,44 +59,40 @@ public class TestWorkDistribution extends AbstractTaskManagerTest { @Autowired private WorkStateManager workStateManager; - private static String taskFilename(String testName, String subId) { - return "src/test/resources/work/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/work/task-" + getTestNumber() + "-" + subId + ".xml"; } - private static String taskFilename(String testName) { - return taskFilename(testName, "0"); + private String taskFilename() { + return taskFilename("0"); } - private static String taskOid(String testName, String subId) { - return "44444444-2222-2222-2222-" + testNumber(testName) + subId + "00000000"; + private String taskOid(String subId) { + return "44444444-2222-2222-2222-" + getTestNumber() + subId + "00000000"; } - private static String taskOid(String test) { - return taskOid(test, "0"); - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid() { + return taskOid("0"); } @NotNull - protected String workerTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "w"); + protected String workerTaskFilename() { + return taskFilename("w"); } @NotNull - protected String coordinatorTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "c"); + protected String coordinatorTaskFilename() { + return taskFilename("c"); } @NotNull - protected String workerTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "w"); + protected String workerTaskOid() { + return taskOid("w"); } @NotNull - protected String coordinatorTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "c"); + protected String coordinatorTaskOid() { + return taskOid("c"); } @PostConstruct @@ -114,20 +110,19 @@ public void test000Integrity() { @Test public void test100AllocateBucket() throws Exception { - final String TEST_NAME = "test100AllocateBucket"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(workerTaskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(workerTaskFilename()); try { - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(TEST_NAME), result); + TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); // WHEN WorkBucketType bucket = workStateManager.getWorkBucket(worker.getOid(), 0, null, null, result); // THEN display("allocated bucket", bucket); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid(), result); TaskQuartzImpl workerAfter = taskManager.getTask(worker.getOid(), result); display("coordinator task after", coordinatorAfter); display("worker task after", workerAfter); @@ -141,17 +136,16 @@ public void test100AllocateBucket() throws Exception { assertOptimizedCompletedBuckets(coordinatorAfter); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test105AllocateBucketStandalone() throws Exception { - final String TEST_NAME = "test105AllocateBucketStandalone"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); try { // WHEN @@ -174,11 +168,10 @@ public void test105AllocateBucketStandalone() throws Exception { @Test public void test107AllocateBucketStandaloneBatched() throws Exception { - final String TEST_NAME = "test107AllocateBucketStandaloneBatched"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); try { // WHEN @@ -200,12 +193,10 @@ public void test107AllocateBucketStandaloneBatched() throws Exception { @Test public void test110AllocateTwoBucketsStandalone() throws Exception { - final String TEST_NAME = "test110AllocateTwoBucketsStandalone"; - - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); try { // WHEN @@ -268,11 +259,10 @@ public void test110AllocateTwoBucketsStandalone() throws Exception { @Test public void test120UnspecifiedBuckets() throws Exception { - final String TEST_NAME = "test120UnspecifiedBuckets"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(taskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(TEST_NAME), result); + TaskQuartzImpl task = taskManager.getTask(taskOid(), result); // WHEN + THEN try { @@ -285,21 +275,20 @@ public void test120UnspecifiedBuckets() throws Exception { @Test public void test130AllocateReleaseCompleteSequence() throws Exception { - final String TEST_NAME = "test130AllocateReleaseCompleteSequence"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); - addObjectFromFile(taskFilename(TEST_NAME, "4")); - addObjectFromFile(taskFilename(TEST_NAME, "5")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); + addObjectFromFile(taskFilename("4")); + addObjectFromFile(taskFilename("5")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); - TaskQuartzImpl worker4 = taskManager.getTask(taskOid(TEST_NAME, "4"), result); - TaskQuartzImpl worker5 = taskManager.getTask(taskOid(TEST_NAME, "5"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); + TaskQuartzImpl worker4 = taskManager.getTask(taskOid("4"), result); + TaskQuartzImpl worker5 = taskManager.getTask(taskOid("5"), result); // WHEN WorkBucketType bucket1 = workStateManager.getWorkBucket(worker1.getOid(), 0, null, null, result); @@ -319,7 +308,7 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { worker2 = taskManager.getTask(worker2.getOid(), result); worker3 = taskManager.getTask(worker3.getOid(), result); worker4 = taskManager.getTask(worker4.getOid(), result); - Task coordinator = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + Task coordinator = taskManager.getTask(coordinatorTaskOid(), result); display("coordinator task after 4+1x allocation", coordinator); display("worker1 task after 4+1x allocation", worker1); display("worker2 task after 4+1x allocation", worker2); @@ -507,25 +496,24 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { assertNoWorkBuckets(worker1.getWorkState()); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test200OneWorkerTask() throws Exception { - final String TEST_NAME = "test200OneWorkerTask"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(workerTaskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(workerTaskFilename()); - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(TEST_NAME), result); + TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); try { // WHEN taskManager.resumeTask(worker, result); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); @@ -535,23 +523,22 @@ public void test200OneWorkerTask() throws Exception { assertTotalSuccessCount(30, singleton(workerAfter)); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test210ThreeWorkersTask() throws Exception { - final String TEST_NAME = "test210ThreeWorkersTask"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); workBucketsTaskHandler.setDelayProcessor(50); @@ -561,7 +548,7 @@ public void test210ThreeWorkersTask() throws Exception { taskManager.resumeTask(worker3, result); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); @@ -587,22 +574,21 @@ public void test210ThreeWorkersTask() throws Exception { // TODO other asserts } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test220WorkerSuspend() throws Exception { - final String TEST_NAME = "test220WorkerSuspend"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); Holder suspensionVictim = new Holder<>(); workBucketsTaskHandler.setProcessor((task, bucket, index) -> { @@ -628,7 +614,7 @@ public void test220WorkerSuspend() throws Exception { // THEN then(); - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitFor("waiting for all items to be processed", () -> getTotalItemsProcessed(coordinatorTaskOid) == 107 - 6, DEFAULT_TIMEOUT, 500); @@ -676,22 +662,21 @@ public void test220WorkerSuspend() throws Exception { // this does not work as processed items from deleted subtask are missing //assertTotalSuccessCount(107 - 6 + 10, coordinatorAfter.listSubtasks(result)); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test230WorkerException() throws Exception { - final String TEST_NAME = "test230WorkerException"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(taskFilename(TEST_NAME, "1")); - addObjectFromFile(taskFilename(TEST_NAME, "2")); - addObjectFromFile(taskFilename(TEST_NAME, "3")); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(taskFilename("1")); + addObjectFromFile(taskFilename("2")); + addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid(TEST_NAME, "1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid(TEST_NAME, "2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid(TEST_NAME, "3"), result); + TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); Holder exceptionVictim = new Holder<>(); workBucketsTaskHandler.setProcessor((task, bucket, index) -> { @@ -713,7 +698,7 @@ public void test230WorkerException() throws Exception { // THEN then(); - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitFor("waiting for all items to be processed", () -> getTotalItemsProcessed(coordinatorTaskOid) == 107 - 6, DEFAULT_TIMEOUT, 500); @@ -769,29 +754,28 @@ public void test230WorkerException() throws Exception { assertOptimizedCompletedBuckets(coordinatorAfter); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } @Test public void test300NarrowQueryOneWorkerTask() throws Exception { - final String TEST_NAME = "test300NarrowQueryOneWorkerTask"; - OperationResult result = createResult(TEST_NAME); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - addObjectFromFile(workerTaskFilename(TEST_NAME)); + OperationResult result = createOperationResult(); + addObjectFromFile(coordinatorTaskFilename()); + addObjectFromFile(workerTaskFilename()); workBucketsTaskHandler.resetBeforeTest(); workBucketsTaskHandler.setDefaultQuery(prismContext.queryFactory().createQuery()); try { - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(TEST_NAME), result); + TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); // WHEN taskManager.resumeTask(worker, result); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); @@ -820,7 +804,7 @@ public void test300NarrowQueryOneWorkerTask() throws Exception { PrismAsserts.assertQueriesEquivalent("Wrong query #2", q2, qe.get(1)); PrismAsserts.assertQueriesEquivalent("Wrong query #3", q3, qe.get(2)); } finally { - suspendAndDeleteTasks(coordinatorTaskOid(TEST_NAME)); + suspendAndDeleteTasks(coordinatorTaskOid()); } } } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java index 1b3a2913d9a..3f64363305a 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java @@ -9,8 +9,6 @@ import static java.util.Collections.singleton; import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; - import java.util.List; import javax.annotation.PostConstruct; import javax.xml.namespace.QName; @@ -48,48 +46,44 @@ public class TestWorkersManagement extends AbstractTaskManagerTest { @Autowired private WorkStateManager workStateManager; @Autowired private CacheConfigurationManager cacheConfigurationManager; - private static String taskFilename(String testName, String subId) { - return "src/test/resources/workers/task-" + testNumber(testName) + "-" + subId + ".xml"; + private String taskFilename(String subId) { + return "src/test/resources/workers/task-" + getTestNumber() + "-" + subId + ".xml"; } @SuppressWarnings("unused") - private static String taskFilename(String testName) { - return taskFilename(testName, "0"); + private String taskFilename() { + return taskFilename("0"); } - private static String taskOid(String testName, String subId) { - return "44444444-2222-2222-2223-" + testNumber(testName) + subId + "00000000"; + private String taskOid(String subId) { + return "44444444-2222-2222-2223-" + getTestNumber() + subId + "00000000"; } @SuppressWarnings("unused") - private static String taskOid(String test) { - return taskOid(test, "0"); - } - - private static String testNumber(String test) { - return test.substring(4, 7); + private String taskOid() { + return taskOid("0"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "w"); + protected String workerTaskFilename() { + return taskFilename("w"); } @NotNull - private String coordinatorTaskFilename(String TEST_NAME) { - return taskFilename(TEST_NAME, "c"); + private String coordinatorTaskFilename() { + return taskFilename("c"); } @SuppressWarnings("unused") @NotNull - protected String workerTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "w"); + protected String workerTaskOid() { + return taskOid("w"); } @NotNull - private String coordinatorTaskOid(String TEST_NAME) { - return taskOid(TEST_NAME, "c"); + private String coordinatorTaskOid() { + return taskOid("c"); } @PostConstruct @@ -110,21 +104,20 @@ public void test000Integrity() { @Test public void test100CreateWorkersSingle() throws Exception { - final String TEST_NAME = "test100CreateWorkersSingle"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); workBucketsTaskHandler.resetBeforeTest(); workBucketsTaskHandler.setDelayProcessor(DEFAULT_SLEEP_INTERVAL); // WHEN - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); + addObjectFromFile(coordinatorTaskFilename()); // THEN - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + String coordinatorTaskOid = coordinatorTaskOid(); try { waitForTaskProgress(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); List workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -148,7 +141,7 @@ public void test100CreateWorkersSingle() throws Exception { // THEN waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -171,23 +164,22 @@ private void displayBucketOpStatistics(String label, Task task) throws SchemaExc @Test public void test110CreateWorkersRecurring() throws Exception { - final String TEST_NAME = "test110CreateWorkersRecurring"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); workBucketsTaskHandler.resetBeforeTest(); workBucketsTaskHandler.setDelayProcessor(DEFAULT_SLEEP_INTERVAL); // (1) ------------------------------------------------------------------------------------ WHEN (import task) when("1: import task"); - addObjectFromFile(coordinatorTaskFilename(TEST_NAME)); - String coordinatorTaskOid = coordinatorTaskOid(TEST_NAME); + addObjectFromFile(coordinatorTaskFilename()); + String coordinatorTaskOid = coordinatorTaskOid(); try { // THEN (worker is created and executed) then("1: import task"); waitForTaskProgress(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); List workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -208,7 +200,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (worker is still present and executed) then("2: wait for coordinator next run"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -225,7 +217,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("3: suspend the tree while work is done"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); Task worker = workers.get(0); @@ -250,7 +242,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are resumed) then("4: resume the tree"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -272,7 +264,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("5: suspend the tree while worker is executing"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -297,7 +289,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("6: resume after 2nd suspend"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(TEST_NAME), result); + coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -321,18 +313,17 @@ public void test110CreateWorkersRecurring() throws Exception { @Test public void test200SimplePartitioning() throws Exception { - final String TEST_NAME = "test200SimplePartitioning"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); partitionedWorkBucketsTaskHandler.resetBeforeTest(); partitionedWorkBucketsTaskHandler.setEnsureSingleRunner(true); partitionedWorkBucketsTaskHandler.setDelayProcessor(1000L); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "r")); + addObjectFromFile(taskFilename("r")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "r"); + String masterTaskOid = taskOid("r"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); @@ -371,18 +362,17 @@ public void test200SimplePartitioning() throws Exception { @Test public void test210PartitioningToWorkersSingleBucket() throws Exception { - final String TEST_NAME = "test210PartitioningToWorkersSingleBucket"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); partitionedWorkBucketsTaskHandler.resetBeforeTest(); partitionedWorkBucketsTaskHandler.setEnsureSingleRunner(true); partitionedWorkBucketsTaskHandler.setDelayProcessor(1000L); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "r")); + addObjectFromFile(taskFilename("r")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "r"); + String masterTaskOid = taskOid("r"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); @@ -436,17 +426,16 @@ public void test210PartitioningToWorkersSingleBucket() throws Exception { @Test public void test220PartitioningToWorkersMoreBuckets() throws Exception { - final String TEST_NAME = "test220PartitioningToWorkersMoreBuckets"; - OperationResult result = createResult(TEST_NAME); + OperationResult result = createOperationResult(); partitionedWorkBucketsTaskHandler.resetBeforeTest(); partitionedWorkBucketsTaskHandler.setDelayProcessor(50L); // WHEN - addObjectFromFile(taskFilename(TEST_NAME, "r")); + addObjectFromFile(taskFilename("r")); // THEN - String masterTaskOid = taskOid(TEST_NAME, "r"); + String masterTaskOid = taskOid("r"); try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); From dbc04d9987aa2066a16660687b541135e2c0cb92 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 00:32:31 +0100 Subject: [PATCH 33/55] removed unnecessary semicolons (except after enum constants) --- .../midpoint/gui/api/component/PopupObjectListPanel.java | 2 +- .../midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java | 2 +- .../evolveum/midpoint/gui/impl/factory/WrapperContext.java | 2 +- .../evolveum/midpoint/gui/impl/prism/ListContainersPopup.java | 2 +- .../web/component/assignment/DelegationEditorPanel.java | 2 +- .../evolveum/midpoint/web/component/data/BoxedTablePanel.java | 2 +- .../web/component/data/column/DoubleButtonColumn.java | 2 +- .../midpoint/web/component/message/FeedbackListView.java | 4 ++-- .../web/component/objectdetails/UserDelegationsTabPanel.java | 2 +- .../web/page/admin/configuration/InternalsCountersPanel.java | 2 +- .../web/page/admin/configuration/InternalsDebugUtilPanel.java | 2 +- .../web/page/admin/configuration/InternalsTracesPanel.java | 2 +- .../web/page/admin/home/dto/PasswordQuestionsDto.java | 2 +- .../evolveum/midpoint/web/page/admin/reports/PageReports.java | 2 +- .../web/page/admin/resources/ResourceContentPanel.java | 2 +- .../web/page/admin/roles/AbstractRoleMemberPanel.java | 2 +- .../web/page/admin/workflow/WorkItemDetailsPanel.java | 2 +- .../midpoint/web/page/forgetpassword/PageForgotPassword.java | 4 ++-- .../midpoint/web/page/self/component/ChangePasswordPanel.java | 2 +- .../web/page/self/component/DashboardSearchPanel.java | 2 +- .../factory/module/AbstractCredentialModuleFactory.java | 2 +- .../web/security/factory/module/LdapModuleFactory.java | 2 +- .../midpoint/common/validator/LegacyValidationMessage.java | 2 +- .../com/evolveum/midpoint/prism/LocalDefinitionStore.java | 2 +- .../notifications/impl/notifiers/SimpleReportNotifier.java | 2 +- .../evolveum/midpoint/report/impl/JRMidpointEvaluator.java | 2 +- .../midpoint/wf/impl/association/TestAddAssociation.java | 2 +- .../evolveum/midpoint/provisioning/util/ProvisioningUtil.java | 2 +- .../midpoint/testing/story/ldap/TestLdapDependency.java | 2 +- .../schrodinger/component/resource/TestConnectionModal.java | 2 -- 30 files changed, 31 insertions(+), 33 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java index 7fda0b71731..321c2e97290 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/component/PopupObjectListPanel.java @@ -62,7 +62,7 @@ protected IColumn, String> createCheckboxColumn() { protected void onUpdateRow(AjaxRequestTarget target, DataTable table, IModel> rowModel, IModel selected) { super.onUpdateRow(target, table, rowModel, selected); onUpdateCheckbox(target, rowModel); - }; + } @Override protected void onUpdateHeader(AjaxRequestTarget target, boolean selected, DataTable table) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java index 7aa67011657..9278e2e1930 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ItemWrapperFactoryImpl.java @@ -84,7 +84,7 @@ private ItemStatus getStatus(I childItem) { public IW createWrapper(Item childItem, ItemStatus status, WrapperContext context) throws SchemaException { return createWrapper(null, (I) childItem, status, context); - }; + } private IW createWrapper(PrismContainerValueWrapper parent, I childItem, ItemStatus status, WrapperContext context) throws SchemaException { IW itemWrapper = createWrapper(parent, childItem, status); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java index 15369c54cb5..efe0dc376ec 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/WrapperContext.java @@ -76,7 +76,7 @@ public boolean isCreateIfEmpty() { public void setCreateIfEmpty(boolean createIfEmpty) { this.createIfEmpty = createIfEmpty; - }; + } public Boolean getReadOnly() { return readOnly; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java index a478bfdcfb4..31921515913 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ListContainersPopup.java @@ -98,7 +98,7 @@ protected void populateItem(ListItem item) { protected boolean getLabelVisible() { return false; - }; + } }; checkFormGroup.getCheck().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java index 225acabd0c0..3c62cab6b96 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/assignment/DelegationEditorPanel.java @@ -490,7 +490,7 @@ public boolean isEnabled(){ body.add(allowTransitive); addAjaxOnUpdateBehavior(body); - }; + } private void addPrivilegesPanel(WebMarkupContainer body){ privilegesNames = getPrivilegesNamesList(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java index 694a0a361a4..3b874a1bc58 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/BoxedTablePanel.java @@ -141,7 +141,7 @@ private int computeRefreshInterval() { public int getAutoRefreshInterval() { return 0; - }; + } public boolean isAutoRefreshEnabled() { return false; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java index b6cf16db227..6f0161200de 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/data/column/DoubleButtonColumn.java @@ -116,7 +116,7 @@ public boolean isSecondEnabled(IModel model){ } public void firstClicked(AjaxRequestTarget target, IModel model){} - public void secondClicked(AjaxRequestTarget target, IModel model){}; + public void secondClicked(AjaxRequestTarget target, IModel model){} public String getFirstSizeCssClass(){ return ButtonSizeClass.SMALL.toString(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java index dd2d7ec12f1..f43d3438c49 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/message/FeedbackListView.java @@ -53,7 +53,7 @@ public void close(AjaxRequestTarget target) { protected void onAfterRender() { opResult.setAlreadyShown(true); super.onAfterRender(); - }; + } }; panel.add(new VisibleEnableBehaviour() { @@ -61,7 +61,7 @@ protected void onAfterRender() { public boolean isVisible() { return !opResult.isAlreadyShown(); - }; + } }); panel.setOutputMarkupId(true); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java index 449ca6a1cfc..1db6ea238c4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/objectdetails/UserDelegationsTabPanel.java @@ -92,7 +92,7 @@ public String getExcludeOid() { public IModel getLabel() { return createStringResource("FocusType.delegations"); - }; + } @Override protected List createAssignmentMenu() { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java index f8b1e7513fa..c8fdd454e16 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsCountersPanel.java @@ -80,7 +80,7 @@ public void onClick(AjaxRequestTarget target) { public void yesPerformed(AjaxRequestTarget target) { getPageBase().getCounterManager().removeCounter(counter); target.add(InternalsCountersPanel.this); - }; + } }; getPageBase().showMainPopup(confirmPanel, target); target.add(InternalsCountersPanel.this); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java index 2bcf4ccf948..6c5a662dfcf 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsDebugUtilPanel.java @@ -63,7 +63,7 @@ protected void onError(AjaxRequestTarget target) { } }; form.add(update); - }; + } private void updateDebugPerformed(AjaxRequestTarget target){ getModelObject().saveDebugUtil(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java index 3f772b2d523..30c4d85be29 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/InternalsTracesPanel.java @@ -83,7 +83,7 @@ protected void onError(AjaxRequestTarget target) { } }; form.add(update); - }; + } private void updateTraces(AjaxRequestTarget target){ for (Entry entry: tracesMap.entrySet()) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java index 4c0ba85da28..e8e3e7a9a8c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/home/dto/PasswordQuestionsDto.java @@ -29,7 +29,7 @@ public class PasswordQuestionsDto implements Serializable{ }*/ public PasswordQuestionsDto(){ - }; + } public PasswordQuestionsDto(String passwQuestion, String passAnswer){ this.passwQuestion = passwQuestion; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java index 5023f565810..e8cb34ef72b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/reports/PageReports.java @@ -227,7 +227,7 @@ protected void runConfirmPerformed(AjaxRequestTarget target, ReportType reportTy PageReports.this.runConfirmPerformed(target, reportType, reportParam); hideMainPopup(target); - }; + } }; showMainPopup(runReportPopupPanel, target); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java index 71a6fbace29..6404482376e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/resources/ResourceContentPanel.java @@ -525,7 +525,7 @@ private List getTasksForKind(List> tasks) { protected void initCustomLayout() { // Nothing to do, for subclass extension - }; + } protected ObjectQuery createQuery() { ObjectQuery baseQuery = null; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java index 2ddcced44f8..fa0d04fe500 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java @@ -855,7 +855,7 @@ protected String getNullValidDisplayValue(){ protected void onUpdate(AjaxRequestTarget target) { refreshAll(target); - }; + } }); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java index 227665f1c91..facbe3e60fc 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/workflow/WorkItemDetailsPanel.java @@ -203,7 +203,7 @@ private void initLayout(){ public boolean isVisible() { return (level != null && level.getFormRef() != null && level.getFormRef().getOid() != null); - }; + } }); if (level != null && level.getFormRef() != null && level.getFormRef().getOid() != null) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java index 0c64025ca8b..c28250a7d5c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/forgetpassword/PageForgotPassword.java @@ -144,7 +144,7 @@ public boolean isVisible() { public boolean isVisible() { return getResetPasswordPolicy().getResetMethod() == ResetMethod.SECURITY_QUESTIONS; - }; + } }); WebMarkupContainer emailContainer = new WebMarkupContainer(ID_EMAIL_CONTAINER); @@ -161,7 +161,7 @@ public boolean isVisible() { public boolean isVisible() { ResetMethod resetMethod = getResetPasswordPolicy().getResetMethod(); return resetMethod == ResetMethod.SECURITY_QUESTIONS || resetMethod == ResetMethod.MAIL; - }; + } }); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java index 7bd299198cf..23323d42848 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/ChangePasswordPanel.java @@ -112,7 +112,7 @@ public boolean isVisible() { public boolean isVisible() { return oldPasswordVisible; - }; + } }); PasswordPanel passwordPanel = new PasswordPanel(ID_PASSWORD_PANEL, new PropertyModel<>(model, MyPasswordsDto.F_PASSWORD)); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java index 178cded1ddd..1db1ce1e0f3 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/self/component/DashboardSearchPanel.java @@ -99,7 +99,7 @@ protected void initLayout() { public IModel getBody() { return searchTypes.get(selectedSearchType); - }; + } @Override protected void onSubmit(AjaxRequestTarget target) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java index d976b320e9d..726b8576a3e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/AbstractCredentialModuleFactory.java @@ -102,7 +102,7 @@ protected AuthenticationProvider getProvider(AbstractCredentialAuthenticationMod } return getObjectObjectPostProcessor().postProcess(createProvider(usedPolicy)); - }; + } protected abstract ModuleAuthentication createEmptyModuleAuthentication(AbstractAuthenticationModuleType moduleType, C configuration); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java index c8c7d3f727e..99280585905 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/security/factory/module/LdapModuleFactory.java @@ -123,7 +123,7 @@ protected AuthenticationProvider getProvider(AuthenticationModuleLdapType module getObjectObjectPostProcessor().postProcess(provider); return provider; - }; + } protected ModuleWebSecurityConfig createModule(ModuleWebSecurityConfiguration configuration) { return getObjectObjectPostProcessor().postProcess(new LdapWebSecurityConfig((LdapModuleWebSecurityConfiguration) configuration)); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java index ce9d9ed0784..c81f8f9f79c 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/LegacyValidationMessage.java @@ -17,7 +17,7 @@ public class LegacyValidationMessage { public enum Type { WARNING, ERROR - }; + } public Type type; public String oid; diff --git a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java index 2de55c702ca..912bd922ebf 100644 --- a/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java +++ b/infra/prism-api/src/main/java/com/evolveum/midpoint/prism/LocalDefinitionStore.java @@ -36,7 +36,7 @@ public interface LocalDefinitionStore { @SuppressWarnings("unchecked") default ID findLocalItemDefinition(@NotNull QName name) { return (ID) findLocalItemDefinition(name, ItemDefinition.class, false); - }; + } @SuppressWarnings("unchecked") default ID findItemDefinition(@NotNull ItemPath path) { diff --git a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java index afaf9a04aa2..c5b7ca4b6b9 100644 --- a/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java +++ b/model/notifications-impl/src/main/java/com/evolveum/midpoint/notifications/impl/notifiers/SimpleReportNotifier.java @@ -138,6 +138,6 @@ protected Trace getLogger() { protected String getContentType() { return "text/html"; - }; + } } diff --git a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java index c2ec57ee205..d44a030386d 100644 --- a/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java +++ b/model/report-impl/src/main/java/com/evolveum/midpoint/report/impl/JRMidpointEvaluator.java @@ -264,7 +264,7 @@ private Object getVariableValue(String name, Mode mode) { } } - enum Mode { DEFAULT, OLD, ESTIMATED }; + enum Mode { DEFAULT, OLD, ESTIMATED } // NOT USED diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java index f1e446bdee6..df698bd1210 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/association/TestAddAssociation.java @@ -360,7 +360,7 @@ void assertsAfterImmediateExecutionFinished(CaseType task, OperationResult resul void assertsRootCaseFinishes(CaseType aCase, List subcases, Task opTask, OperationResult result) throws Exception { } boolean decideOnApproval(CaseType subcase, ApprovalContextType wfContext) throws Exception { return true; } - String getObjectOid(CaseType task, OperationResult result) throws SchemaException { return null; }; + String getObjectOid(CaseType task, OperationResult result) throws SchemaException { return null; } boolean removeAssignmentsBeforeTest() { return true; } } diff --git a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java index 1dfd1151287..1cb8bfc36d0 100644 --- a/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java +++ b/provisioning/provisioning-impl/src/main/java/com/evolveum/midpoint/provisioning/util/ProvisioningUtil.java @@ -77,7 +77,7 @@ public class ProvisioningUtil { private static final QName FAKE_SCRIPT_ARGUMENT_NAME = new QName(SchemaConstants.NS_C, "arg"); public static final Duration DEFAULT_OPERATION_RETRY_PERIOD_DURATION = XmlTypeConverter.createDuration("PT30M"); public static final int DEFAULT_OPERATION_RETRY_MAX_ATTEMPTS = 3; - private static final Duration DEFAULT_PENDING_OPERATION_RETENTION_PERIOD_DURATION = XmlTypeConverter.createDuration("P1D");; + private static final Duration DEFAULT_PENDING_OPERATION_RETENTION_PERIOD_DURATION = XmlTypeConverter.createDuration("P1D"); public static final Duration DEFAULT_DEAD_SHADOW_RETENTION_PERIOD_DURATION = XmlTypeConverter.createDuration("P7D"); private static final Trace LOGGER = TraceManager.getTrace(ProvisioningUtil.class); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java index d9f3d2ad58f..b18af1cb09a 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java @@ -450,7 +450,7 @@ private void assertLdapObject(PrismObject org, ShadowKindType kind, Str if (LDAP_OU_VIP_INTENT.equals(intent)) search = "ou="+orgName+"-vip"; } Entry objEntry = openDJController.searchSingle(search); - assertNotNull("No LDAP entry for "+orgName, objEntry);; + assertNotNull("No LDAP entry for "+orgName, objEntry); display("LDAP entry kind " +kind + " inten " + intent +" ldapObj", objEntry); if (kind.equals(ShadowKindType.ENTITLEMENT)){ diff --git a/tools/schrodinger/src/main/java/com/evolveum/midpoint/schrodinger/component/resource/TestConnectionModal.java b/tools/schrodinger/src/main/java/com/evolveum/midpoint/schrodinger/component/resource/TestConnectionModal.java index 1f4a1df61f7..dcc39f46584 100644 --- a/tools/schrodinger/src/main/java/com/evolveum/midpoint/schrodinger/component/resource/TestConnectionModal.java +++ b/tools/schrodinger/src/main/java/com/evolveum/midpoint/schrodinger/component/resource/TestConnectionModal.java @@ -147,8 +147,6 @@ public boolean isTestFailure() { return isFailure; } - ; - public T clickOk() { $(Schrodinger.byDataId("ok")) From 4614a5b10959dc19a8d9ce9baa07cf794ffd69c8 Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Mon, 9 Mar 2020 05:45:12 +0100 Subject: [PATCH 34/55] bringing back expression panel for associations and attributes outbound mappings. small cleanup, some tries for improving look&feel. (relates to MID-6060) --- .../AssociationAndExpressionPanelFactory.java | 55 ++++ .../factory/ExpressionWrapperFactory.java | 3 - .../impl/prism/PrismContainerValuePanel.java | 5 - .../component/ExpressionPropertyPanel.html | 40 ++- .../component/ExpressionPropertyPanel.java | 309 ++++++++---------- .../AssociationExpressionValuePanel.html | 64 ++-- .../input/SimpleValueExpressionPanel.html | 44 +-- 7 files changed, 271 insertions(+), 249 deletions(-) create mode 100644 gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/AssociationAndExpressionPanelFactory.java diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/AssociationAndExpressionPanelFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/AssociationAndExpressionPanelFactory.java new file mode 100644 index 00000000000..a8fb2c6caf6 --- /dev/null +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/AssociationAndExpressionPanelFactory.java @@ -0,0 +1,55 @@ +/* + * Copyright (c) 2010-2018 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.gui.impl.factory; + +import javax.annotation.PostConstruct; + +import org.apache.wicket.markup.html.panel.Panel; +import org.springframework.stereotype.Component; + +import com.evolveum.midpoint.gui.api.factory.AbstractGuiComponentFactory; +import com.evolveum.midpoint.gui.api.prism.ItemWrapper; +import com.evolveum.midpoint.gui.impl.prism.ExpressionWrapper; +import com.evolveum.midpoint.web.component.input.AssociationExpressionValuePanel; +import com.evolveum.midpoint.web.component.input.SimpleValueExpressionPanel; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; + +@Component +public class AssociationAndExpressionPanelFactory extends AbstractGuiComponentFactory { + + @PostConstruct + public void register() { + getRegistry().addToRegistry(this); + } + + @Override + protected Panel getPanel(PrismPropertyPanelContext panelCtx) { + ExpressionWrapper expressionWrapper = (ExpressionWrapper) panelCtx.unwrapWrapperModel(); + + if (expressionWrapper.isAttributeExpression()) { + return new SimpleValueExpressionPanel(panelCtx.getComponentId(), panelCtx.getRealValueModel()); + } + + return new AssociationExpressionValuePanel(panelCtx.getComponentId(), panelCtx.getRealValueModel(), expressionWrapper.getConstruction()); + + } + + @Override + public boolean match(IW wrapper) { + if (wrapper == null) { + return false; + } + + if (!(wrapper instanceof ExpressionWrapper)) { + return false; + } + ExpressionWrapper expressionWrapper = (ExpressionWrapper) wrapper; + return expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression(); + } + + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java index 27c767708c1..81e1066a080 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ExpressionWrapperFactory.java @@ -48,9 +48,6 @@ public int getOrder() { protected PrismPropertyWrapper createWrapper(PrismContainerValueWrapper parent, PrismProperty item, ItemStatus status) { - if (parent != null && parent.getParent() != null && QNameUtil.match(parent.getParent().getTypeName(), MappingType.COMPLEX_TYPE)) { - return super.createWrapper(parent, item, status); - } ExpressionWrapper propertyWrapper = new ExpressionWrapper(parent, item, status); getRegistry().registerWrapperPanel(item.getDefinition().getTypeName(), ExpressionPropertyPanel.class); return propertyWrapper; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java index 869fb2830ff..e4332d9ee69 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValuePanel.java @@ -79,16 +79,11 @@ public class PrismContainerValuePanel model, ItemPanelSettings settings) { super(id, model); this.settings = settings; -// this.visibilityHandler = visibilityHandler; -// this.editabilityHandler = editabilityHandler; } @Override diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html index d2882ee6181..939c0f006a0 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.html @@ -1,18 +1,22 @@ - - - - - -

-
-
-
-
-
- - + + + + + +
+
+
+
+
+
+ +
+
+
+ + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java index c9dcd24c706..002ec29b60b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/component/ExpressionPropertyPanel.java @@ -1,172 +1,137 @@ -/* - * Copyright (c) 2010-2018 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.gui.impl.prism.component; - -import com.evolveum.midpoint.gui.api.factory.GuiComponentFactory; -import com.evolveum.midpoint.gui.api.model.ReadOnlyValueModel; -import com.evolveum.midpoint.gui.impl.factory.ExpressionModel; -import com.evolveum.midpoint.gui.impl.factory.ItemRealValueModel; -import com.evolveum.midpoint.gui.impl.factory.WrapperContext; -import com.evolveum.midpoint.gui.impl.prism.*; -import com.evolveum.midpoint.prism.PrismPropertyValue; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.web.component.input.AssociationExpressionValuePanel; -import com.evolveum.midpoint.web.component.input.SimpleValueExpressionPanel; -import com.evolveum.midpoint.web.component.input.TextPanel; -import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.web.component.util.VisibleBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnBlurAjaxFormUpdatingBehaviour; -import com.evolveum.midpoint.web.page.admin.configuration.component.EmptyOnChangeAjaxFormUpdatingBehavior; -import com.evolveum.midpoint.web.page.admin.reports.component.AceEditorPanel; -import com.evolveum.midpoint.web.util.ExpressionUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; -import org.apache.commons.collections.CollectionUtils; -import org.apache.wicket.Component; -import org.apache.wicket.ajax.AjaxRequestTarget; -import org.apache.wicket.markup.html.list.ListItem; -import org.apache.wicket.markup.html.panel.Panel; -import org.apache.wicket.model.IModel; -import org.apache.wicket.model.Model; - -import java.util.Arrays; - -/** - * @author katka - * - */ -public class ExpressionPropertyPanel extends PrismPropertyPanel { - - private static final long serialVersionUID = 1L; - - private static final Trace LOGGER = TraceManager.getTrace(ExpressionPropertyPanel.class); - - private static final String ID_EXPRESSION_PANEL = "expressionPanel"; - private static final String ID_HEADER = "header"; - - private boolean isExpanded; - - public ExpressionPropertyPanel(String id, IModel> model, ItemPanelSettings settings) { - super(id, model, settings); - isExpanded = model.getObject() != null && CollectionUtils.isNotEmpty(model.getObject().getValues()); - //todo how to set displayOrder ? to display expression property the last, in the same way as containers - } - - @Override - protected Panel createHeaderPanel() { - ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); - if (expressionWrapper != null && (expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression())){ - return new ExpressionPropertyHeaderPanel(ID_HEADER, getModel()) { - private static final long serialVersionUID = 1L; - - @Override - protected void onExpandClick(AjaxRequestTarget target) { - super.onExpandClick(target); - isExpanded = !isExpanded; - target.add(ExpressionPropertyPanel.this); - } - - @Override - protected void addExpressionValuePerformed(AjaxRequestTarget target) { - ExpressionPropertyPanel.this.addExpressionValuePerformed(target); - } - - @Override - protected void removeExpressionValuePerformed(AjaxRequestTarget target){ - ExpressionPropertyPanel.this.getModelObject().getValues().clear(); - target.add(ExpressionPropertyPanel.this); - } - }; - } else { - return super.createHeaderPanel(); - } - } - - @Override - protected Component createValuePanel(ListItem> item, GuiComponentFactory factory, ItemVisibilityHandler visibilityHandler, - ItemEditabilityHandler editabilityHandler) { - ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); - Component expressionPanel = null; - if (expressionWrapper != null && (expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression())) { - ItemRealValueModel realValueModel = new ItemRealValueModel(item.getModel()); - if (expressionWrapper.isAttributeExpression()) { - expressionPanel = new SimpleValueExpressionPanel(ID_EXPRESSION_PANEL, realValueModel); - } else if (expressionWrapper.isAssociationExpression()) { - expressionPanel = new AssociationExpressionValuePanel(ID_EXPRESSION_PANEL, realValueModel, expressionWrapper.getConstruction()); - } - expressionPanel.setOutputMarkupId(true); - expressionPanel.add(new VisibleBehaviour(() -> isExpanded)); - item.add(expressionPanel); - } else { - ItemRealValueModel realValueModel = new ItemRealValueModel(item.getModel()); - expressionPanel = new AceEditorPanel(ID_EXPRESSION_PANEL, null, new ExpressionModel(realValueModel, getPageBase()), 200){ - @Override - protected boolean isResizeToMaxHeight() { - return false; - } - }; - ((AceEditorPanel)expressionPanel).getEditor().add(new EmptyOnBlurAjaxFormUpdatingBehaviour()); - ((AceEditorPanel)expressionPanel).getEditor().add(new EmptyOnChangeAjaxFormUpdatingBehavior()); - expressionPanel.add(new VisibleBehaviour(() -> isExpanded)); - item.add(expressionPanel); - } - - return expressionPanel; - } - - private void addExpressionValuePerformed(AjaxRequestTarget target){ - ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); - if (expressionWrapper.isAttributeExpression()){ - expressionValueAddPerformed(target, ExpressionValueTypes.LITERAL_VALUE_EXPRESSION); - } else { - ExpressionTypeSelectPopup expressionTypeSelectPopup = new ExpressionTypeSelectPopup(getPageBase().getMainPopupBodyId()) { - private static final long serialVersionUID = 1L; - - @Override - protected void addExpressionPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType) { - expressionValueAddPerformed(target, expressionType); - } - }; - getPageBase().showMainPopup(expressionTypeSelectPopup, target); - } - } - - private void expressionValueAddPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType){ - getPageBase().hideMainPopup(target); - try { - ExpressionType newExpressionValue = new ExpressionType(); - if (ExpressionValueTypes.SHADOW_REF_EXPRESSION.equals(expressionType)){ - ExpressionUtil.addShadowRefEvaluatorValue(newExpressionValue, null, getPrismContext()); - } else if (ExpressionValueTypes.ASSOCIATION_TARGET_SEARCH_EXPRESSION.equals(expressionType)){ - ExpressionUtil.getOrCreateAssociationTargetSearchValues(newExpressionValue, getPrismContext()); - } else if (ExpressionValueTypes.LITERAL_VALUE_EXPRESSION.equals(expressionType)){ - ExpressionUtil.updateLiteralExpressionValue(newExpressionValue, Arrays.asList(""), getPrismContext()); - } - - WrapperContext context = new WrapperContext(null, null); - PrismPropertyValue expressionValue = getPageBase().getPrismContext().itemFactory().createPropertyValue(newExpressionValue); - PrismPropertyValueWrapper newExpressionValueWrapper = (PrismPropertyValueWrapper) getPageBase() - .createValueWrapper(getModelObject(), expressionValue, ValueStatus.ADDED, context); - - getModelObject().getValues().clear(); - getModelObject().getValues().add(newExpressionValueWrapper); - getModelObject().getItem().setRealValue(newExpressionValue); - } catch (SchemaException ex){ - LOGGER.error("Unable to create new expression value: {}", ex.getLocalizedMessage()); - } - - target.add(ExpressionPropertyPanel.this); - - } - - @Override - protected void createButtons(ListItem> item) { - //nothing to do.. buttons are in the prism container panel header/ prism container value header - } - -} +/* + * Copyright (c) 2010-2018 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.gui.impl.prism.component; + +import java.util.Collections; + +import org.apache.commons.collections.CollectionUtils; +import org.apache.wicket.Component; +import org.apache.wicket.ajax.AjaxRequestTarget; +import org.apache.wicket.markup.html.list.ListItem; +import org.apache.wicket.markup.html.panel.Panel; +import org.apache.wicket.model.IModel; + +import com.evolveum.midpoint.gui.api.factory.GuiComponentFactory; +import com.evolveum.midpoint.gui.impl.factory.WrapperContext; +import com.evolveum.midpoint.gui.impl.prism.*; +import com.evolveum.midpoint.prism.PrismPropertyValue; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.logging.Trace; +import com.evolveum.midpoint.util.logging.TraceManager; +import com.evolveum.midpoint.web.component.prism.ValueStatus; +import com.evolveum.midpoint.web.component.util.VisibleBehaviour; +import com.evolveum.midpoint.web.util.ExpressionUtil; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ExpressionType; + +/** + * @author katka + * + */ +public class ExpressionPropertyPanel extends PrismPropertyPanel { + + private static final long serialVersionUID = 1L; + + private static final Trace LOGGER = TraceManager.getTrace(ExpressionPropertyPanel.class); + + private static final String ID_HEADER = "header"; + + private boolean isExpanded; + + public ExpressionPropertyPanel(String id, IModel> model, ItemPanelSettings settings) { + super(id, model, settings); + isExpanded = model.getObject() != null && CollectionUtils.isNotEmpty(model.getObject().getValues()); + //todo how to set displayOrder ? to display expression property the last, in the same way as containers + } + + @Override + protected Panel createHeaderPanel() { + ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); + if (expressionWrapper != null && (expressionWrapper.isAssociationExpression() || expressionWrapper.isAttributeExpression())){ + return new ExpressionPropertyHeaderPanel(ID_HEADER, getModel()) { + private static final long serialVersionUID = 1L; + + @Override + protected void onExpandClick(AjaxRequestTarget target) { + super.onExpandClick(target); + isExpanded = !isExpanded; + target.add(ExpressionPropertyPanel.this); + } + + @Override + protected void addExpressionValuePerformed(AjaxRequestTarget target) { + ExpressionPropertyPanel.this.addExpressionValuePerformed(target); + } + + @Override + protected void removeExpressionValuePerformed(AjaxRequestTarget target){ + ExpressionPropertyPanel.this.getModelObject().getValues().clear(); + target.add(ExpressionPropertyPanel.this); + } + }; + } else { + return super.createHeaderPanel(); + } + } + + @Override + protected Component createValuePanel(ListItem> item, GuiComponentFactory factory, ItemVisibilityHandler visibilityHandler, + ItemEditabilityHandler editabilityHandler) { + Component expressionPanel = super.createValuePanel(item, factory, visibilityHandler, editabilityHandler); + expressionPanel.add(new VisibleBehaviour(() -> isExpanded)); + return expressionPanel; + } + + private void addExpressionValuePerformed(AjaxRequestTarget target){ + ExpressionWrapper expressionWrapper = (ExpressionWrapper) getModelObject(); + if (expressionWrapper.isAttributeExpression()){ + expressionValueAddPerformed(target, ExpressionValueTypes.LITERAL_VALUE_EXPRESSION); + } else { + ExpressionTypeSelectPopup expressionTypeSelectPopup = new ExpressionTypeSelectPopup(getPageBase().getMainPopupBodyId()) { + private static final long serialVersionUID = 1L; + + @Override + protected void addExpressionPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType) { + expressionValueAddPerformed(target, expressionType); + } + }; + getPageBase().showMainPopup(expressionTypeSelectPopup, target); + } + } + + private void expressionValueAddPerformed(AjaxRequestTarget target, ExpressionValueTypes expressionType){ + getPageBase().hideMainPopup(target); + try { + ExpressionType newExpressionValue = new ExpressionType(); + if (ExpressionValueTypes.SHADOW_REF_EXPRESSION.equals(expressionType)){ + ExpressionUtil.addShadowRefEvaluatorValue(newExpressionValue, null, getPrismContext()); + } else if (ExpressionValueTypes.ASSOCIATION_TARGET_SEARCH_EXPRESSION.equals(expressionType)){ + ExpressionUtil.getOrCreateAssociationTargetSearchValues(newExpressionValue, getPrismContext()); + } else if (ExpressionValueTypes.LITERAL_VALUE_EXPRESSION.equals(expressionType)){ + ExpressionUtil.updateLiteralExpressionValue(newExpressionValue, Collections.singletonList(""), getPrismContext()); + } + + WrapperContext context = new WrapperContext(null, null); + PrismPropertyValue expressionValue = getPageBase().getPrismContext().itemFactory().createPropertyValue(newExpressionValue); + PrismPropertyValueWrapper newExpressionValueWrapper = getPageBase().createValueWrapper(getModelObject(), expressionValue, ValueStatus.ADDED, context); + + getModelObject().getValues().clear(); + getModelObject().getValues().add(newExpressionValueWrapper); + getModelObject().getItem().setRealValue(newExpressionValue); + } catch (SchemaException ex){ + LOGGER.error("Unable to create new expression value: {}", ex.getLocalizedMessage()); + } + + target.add(ExpressionPropertyPanel.this); + + } + + @Override + protected void createButtons(ListItem> item) { + //nothing to do.. buttons are in the prism container panel header/ prism container value header + } + +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html index ce818c74f08..1fee985f83e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/AssociationExpressionValuePanel.html @@ -1,30 +1,34 @@ - - - - - - -
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- - - + + + + + + +
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ + + diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html index f4f55743b23..46e94bd4463 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/component/input/SimpleValueExpressionPanel.html @@ -1,21 +1,23 @@ - - - - - - -
-
-
-
-
-
- - - - + + + + + + +
+
+
+
+
+
+
+
+ + + + From 8da2239b042d759d2f28fcb2aa627ee43dd987b0 Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Mon, 9 Mar 2020 06:59:00 +0100 Subject: [PATCH 35/55] MID-2353 - errors count column for task list. doesn't work for partitioned tasks yet. --- .../web/page/admin/server/PageTasks.java | 1 + .../server/TaskOperationStatisticsPanel.java | 57 +++-- .../web/page/admin/server/TaskTablePanel.java | 25 ++- .../midpoint/schema/util/TaskTypeUtil.java | 200 +++++++++++------- 4 files changed, 172 insertions(+), 111 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java index 1ff15955a20..ab16a4fd84e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java @@ -186,6 +186,7 @@ private Collection> createOperationOptions( propertiesToGet.add(TaskType.F_NODE_AS_OBSERVED); propertiesToGet.add(TaskType.F_NEXT_RUN_START_TIMESTAMP); propertiesToGet.add(TaskType.F_NEXT_RETRY_TIMESTAMP); + propertiesToGet.add(TaskType.F_SUBTASK); GetOperationOptionsBuilder getOperationOptionsBuilder = getSchemaHelper().getOperationOptionsBuilder(); getOperationOptionsBuilder = getOperationOptionsBuilder.resolveNames(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java index f9998829cf0..974cfaa0044 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java @@ -37,6 +37,7 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; +import java.util.stream.Stream; public class TaskOperationStatisticsPanel extends BasePanel> implements TaskTabPanel { @@ -69,29 +70,39 @@ private LoadableModel createOperationStatsModel() { protected OperationStatsType load() { PrismObject task = getModelObject().getObject(); - IterativeTaskInformationType iterativeTaskInformation = new IterativeTaskInformationType(); - SynchronizationInformationType synchronizationInformation = new SynchronizationInformationType(); - ActionsExecutedInformationType actionsExecutedInformation = new ActionsExecutedInformationType(); - - if (TaskTypeUtil.isPartitionedMaster(task.asObjectable())) { - List subTasks = resolveSubTasks(); - for (TaskType taskDto : subTasks) { - OperationStatsType operationStats = taskDto.getOperationStats(); - if (operationStats != null) { - IterativeTaskInformation.addTo(iterativeTaskInformation, operationStats.getIterativeTaskInformation(), true); - SynchronizationInformation.addTo(synchronizationInformation, operationStats.getSynchronizationInformation()); - ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStats.getActionsExecutedInformation()); - } - } - - return new OperationStatsType(getPrismContext()) - .iterativeTaskInformation(iterativeTaskInformation) - .synchronizationInformation(synchronizationInformation) - .actionsExecutedInformation(actionsExecutedInformation); - - } - - return task.asObjectable().getOperationStats(); + return TaskTypeUtil.getAggregatedOperationStats(task.asObjectable(), getPrismContext()); +// IterativeTaskInformationType iterativeTaskInformation = new IterativeTaskInformationType(); +// SynchronizationInformationType synchronizationInformation = new SynchronizationInformationType(); +// ActionsExecutedInformationType actionsExecutedInformation = new ActionsExecutedInformationType(); +// +// if (TaskTypeUtil.isPartitionedMaster(task.asObjectable())) { +//// List subTasks = resolveSubTasks(); +// Stream subTasks = TaskTypeUtil.getAllTasksStream(task.asObjectable()); +// subTasks.forEach(subTask -> { +// OperationStatsType operationStatsType = subTask.getOperationStats(); +// if (operationStatsType != null) { +// IterativeTaskInformation.addTo(iterativeTaskInformation, operationStatsType.getIterativeTaskInformation(), true); +// SynchronizationInformation.addTo(synchronizationInformation, operationStatsType.getSynchronizationInformation()); +// ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStatsType.getActionsExecutedInformation()); +// } +// }); +//// for (TaskType taskDto : subTasks) { +//// OperationStatsType operationStats = taskDto.getOperationStats(); +//// if (operationStats != null) { +//// IterativeTaskInformation.addTo(iterativeTaskInformation, operationStats.getIterativeTaskInformation(), true); +//// SynchronizationInformation.addTo(synchronizationInformation, operationStats.getSynchronizationInformation()); +//// ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStats.getActionsExecutedInformation()); +//// } +//// } +// +// return new OperationStatsType(getPrismContext()) +// .iterativeTaskInformation(iterativeTaskInformation) +// .synchronizationInformation(synchronizationInformation) +// .actionsExecutedInformation(actionsExecutedInformation); +// +// } +// +// return task.asObjectable().getOperationStats(); } }; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java index 1c61d996ac4..067327d2ec2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTablePanel.java @@ -46,6 +46,7 @@ import org.apache.wicket.ajax.AjaxRequestTarget; import org.apache.wicket.behavior.AttributeAppender; import org.apache.wicket.extensions.markup.html.repeater.data.grid.ICellPopulator; +import org.apache.wicket.extensions.markup.html.repeater.data.table.AbstractColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.IColumn; import org.apache.wicket.extensions.markup.html.repeater.data.table.export.AbstractExportableColumn; import org.apache.wicket.markup.html.WebMarkupContainer; @@ -227,6 +228,7 @@ protected List, String>> initCustomTaskColumns( columns.add(createTaskExecutionStatusColumn()); columns.add(createProgressColumn("pageTasks.task.progress")); + columns.add(createErrorsColumn("pageTasks.task.errors")); columns.add(new IconColumn>(createStringResource("pageTasks.task.status"), TaskType.F_RESULT_STATUS.getLocalPart()) { @@ -296,6 +298,17 @@ public IModel getDataModel(IModel> rowModel) { }; } + private AbstractColumn, String> createErrorsColumn(String titleKey) { + return new AbstractColumn, String>(createStringResource(titleKey)) { + @Override + public void populateItem(Item>> cellItem, String componentId, IModel> rowModel) { + TaskType task = rowModel.getObject().getValue(); + cellItem.add(new Label(componentId, new Model<>(TaskTypeUtil.getObjectsProcessedFailures(task, getPrismContext())))); + + } + }; + } + private String getProgressDescription(SelectableBean task) { Long stalledSince = getStalledSince(task.getValue()); if (stalledSince != null) { @@ -415,7 +428,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); boolean visible = WebComponentUtil.canSuspendTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase()); return Model.of(visible); } @@ -452,7 +465,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); boolean visible = WebComponentUtil.canResumeTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase()); return Model.of(visible); } @@ -490,7 +503,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); return Model.of(WebComponentUtil.canRunNowTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase())); } @@ -664,7 +677,7 @@ public IModel getVisible() { if (rowModel == null){ return Model.of(Boolean.TRUE); } - SelectableBean rowModelObj = (SelectableBean)rowModel.getObject(); + SelectableBean rowModelObj = rowModel.getObject(); return Model.of(WebComponentUtil.canSuspendTask(rowModelObj.getValue(), TaskTablePanel.this.getPageBase())); } @@ -843,12 +856,8 @@ private void deleteTaskConfirmedPerformed(AjaxRequestTarget target, IModel> task) { diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java index 9f475446d73..43c5ab206ae 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java @@ -1,80 +1,120 @@ -/* - * Copyright (c) 2010-2018 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.schema.util; - -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - -import org.jetbrains.annotations.NotNull; - -import java.util.*; -import java.util.stream.Stream; - -/** - * @author mederly - */ -public class TaskTypeUtil { - - /** - * Returns a stream of the task and all of its subtasks. - */ - @NotNull - public static Stream getAllTasksStream(TaskType root) { - return Stream.concat(Stream.of(root), - getResolvedSubtasks(root).stream().flatMap(TaskTypeUtil::getAllTasksStream)); - } - - public static List getResolvedSubtasks(TaskType parent) { - List rv = new ArrayList<>(); - for (ObjectReferenceType childRef : parent.getSubtaskRef()) { - //noinspection unchecked - PrismObject child = childRef.getObject(); - if (child != null) { - rv.add(child.asObjectable()); - } else { - throw new IllegalStateException("Unresolved subtaskRef in " + parent + ": " + childRef); - } - } - return rv; - } - - public static void addSubtask(TaskType parent, TaskType child, PrismContext prismContext) { - parent.getSubtaskRef().add(ObjectTypeUtil.createObjectRefWithFullObject(child, prismContext)); - } - - //moved from GUI - public static boolean isCoordinator(TaskType task) { - return getKind(task) == TaskKindType.COORDINATOR; - } - - public static boolean isPartitionedMaster(TaskType task) { - return getKind(task) == TaskKindType.PARTITIONED_MASTER; - } - - @NotNull - public static TaskKindType getKind(TaskType task) { - if (task.getWorkManagement() != null && task.getWorkManagement().getTaskKind() != null) { - return task.getWorkManagement().getTaskKind(); - } else { - return TaskKindType.STANDALONE; - } - } - - public static int getObjectsProcessed(TaskType task) { - OperationStatsType stats = task.getOperationStats(); - if (stats == null) { - return 0; - } - IterativeTaskInformationType iterativeStats = stats.getIterativeTaskInformation(); - if (iterativeStats == null) { - return 0; - } - return iterativeStats.getTotalSuccessCount() + iterativeStats.getTotalFailureCount(); - } -} +/* + * Copyright (c) 2010-2018 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.schema.util; + +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.schema.statistics.ActionsExecutedInformation; +import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; +import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +import org.jetbrains.annotations.NotNull; + +import java.util.*; +import java.util.stream.Stream; + +/** + * @author mederly + */ +public class TaskTypeUtil { + + /** + * Returns a stream of the task and all of its subtasks. + */ + @NotNull + public static Stream getAllTasksStream(TaskType root) { + return Stream.concat(Stream.of(root), + getResolvedSubtasks(root).stream().flatMap(TaskTypeUtil::getAllTasksStream)); + } + + public static List getResolvedSubtasks(TaskType parent) { + List rv = new ArrayList<>(); + for (ObjectReferenceType childRef : parent.getSubtaskRef()) { + //noinspection unchecked + PrismObject child = childRef.getObject(); + if (child != null) { + rv.add(child.asObjectable()); + } else { + throw new IllegalStateException("Unresolved subtaskRef in " + parent + ": " + childRef); + } + } + return rv; + } + + public static void addSubtask(TaskType parent, TaskType child, PrismContext prismContext) { + parent.getSubtaskRef().add(ObjectTypeUtil.createObjectRefWithFullObject(child, prismContext)); + } + + //moved from GUI + public static boolean isCoordinator(TaskType task) { + return getKind(task) == TaskKindType.COORDINATOR; + } + + public static boolean isPartitionedMaster(TaskType task) { + return getKind(task) == TaskKindType.PARTITIONED_MASTER; + } + + @NotNull + public static TaskKindType getKind(TaskType task) { + if (task.getWorkManagement() != null && task.getWorkManagement().getTaskKind() != null) { + return task.getWorkManagement().getTaskKind(); + } else { + return TaskKindType.STANDALONE; + } + } + + public static int getObjectsProcessed(TaskType task) { + OperationStatsType stats = task.getOperationStats(); + if (stats == null) { + return 0; + } + IterativeTaskInformationType iterativeStats = stats.getIterativeTaskInformation(); + if (iterativeStats == null) { + return 0; + } + return iterativeStats.getTotalSuccessCount() + iterativeStats.getTotalFailureCount(); + } + + public static int getObjectsProcessedFailures(TaskType task, PrismContext prismContext) { + OperationStatsType stats = getAggregatedOperationStats(task, prismContext); + if (stats == null) { + return 0; + } + IterativeTaskInformationType iterativeStats = stats.getIterativeTaskInformation(); + if (iterativeStats == null) { + return 0; + } + return iterativeStats.getTotalFailureCount(); + } + + public static OperationStatsType getAggregatedOperationStats(TaskType task, PrismContext prismContext) { + if (!isPartitionedMaster(task)) { + return task.getOperationStats(); + } + + IterativeTaskInformationType iterativeTaskInformation = new IterativeTaskInformationType(); + SynchronizationInformationType synchronizationInformation = new SynchronizationInformationType(); + ActionsExecutedInformationType actionsExecutedInformation = new ActionsExecutedInformationType(); + + Stream subTasks = TaskTypeUtil.getAllTasksStream(task); + subTasks.forEach(subTask -> { + OperationStatsType operationStatsType = subTask.getOperationStats(); + if (operationStatsType != null) { + IterativeTaskInformation.addTo(iterativeTaskInformation, operationStatsType.getIterativeTaskInformation(), true); + SynchronizationInformation.addTo(synchronizationInformation, operationStatsType.getSynchronizationInformation()); + ActionsExecutedInformation.addTo(actionsExecutedInformation, operationStatsType.getActionsExecutedInformation()); + } + }); + + return new OperationStatsType(prismContext) + .iterativeTaskInformation(iterativeTaskInformation) + .synchronizationInformation(synchronizationInformation) + .actionsExecutedInformation(actionsExecutedInformation); + } +} From b09ce89b5a2dc684816ed0e6efeac9a56fd211e4 Mon Sep 17 00:00:00 2001 From: Radovan Semancik Date: Mon, 9 Mar 2020 11:09:42 +0100 Subject: [PATCH 36/55] Experiments with AD connector --- pom.xml | 4221 +++++++-------- testing/conntest/pom.xml | 5 + .../AbstractLdapSynchronizationTest.java | 1027 ++-- .../ad/AbstractAdLdapMultidomainTest.java | 4693 +++++++++-------- .../conntest/ad/AbstractAdLdapTest.java | 2513 +++++---- .../ad-ldap-multidomain/resource-chimera.xml | 1711 +++--- .../ad-ldap-multidomain/task-sync.xml | 28 + .../src/test/resources/logback-test.xml | 141 +- 8 files changed, 7227 insertions(+), 7112 deletions(-) create mode 100644 testing/conntest/src/test/resources/ad-ldap-multidomain/task-sync.xml diff --git a/pom.xml b/pom.xml index 5cf468d864b..f2b01b435d7 100644 --- a/pom.xml +++ b/pom.xml @@ -1,2108 +1,2113 @@ - - - - - 4.0.0 - - - - com.evolveum.midpoint - midpoint - 4.1-SNAPSHOT - pom - - midPoint Project - Utility module to compile all of the maven based midPoint projects. - - evolveum - https://www.evolveum.com - - - - Apache License v2.0 - https://www.apache.org/licenses/LICENSE-2.0.txt - repo - - - European Union Public License - https://joinup.ec.europa.eu/collection/eupl/eupl-text-11-12 - repo - - - - - tools - infra - repo - provisioning - model - custom - gui - icf-connectors - testing - - - - https://github.com/Evolveum/midpoint.git - git@github.com:Evolveum/midpoint.git - https://github.com/Evolveum/midpoint.git - - - Atlassian JIRA - https://jira.evolveum.com/browse/MID - - - - evolveum-nexus - Internal Releases - https://nexus.evolveum.com/nexus/content/repositories/releases/ - - - evolveum-nexus - Internal Snapshots - https://nexus.evolveum.com/nexus/content/repositories/snapshots/ - - - - - - - UTF-8 - 1.8 - en_US - true - false - false - - - ${describe} - ${maven.build.timestamp} - EEE, d MMM yyyy HH:mm:ss Z - - - -Xms1024m -Xmx4096m - -Xms1024m -Xmx4096m -Duser.language=en - - full - - true - - - 2.6 - 2.6 - 3.7 - 1.2 - 3.3.1 - 3.3.0 - 2.2.0 - 2.4.7 - 2.3.1 - 2.3.0.1 - 2.3.0.1 - 2.6.2 - 2.3.0.e3 - 3.141.59 - 1.7.25 - 1.2.3 - 2.1.8.RELEASE - - 5.1.9.RELEASE - 5.1.6.RELEASE - 2.0.0.M30 - 1.2.1.Final - 3.5.0 - 6.14.3 - 1.2 - 2.1.1 - 2.2.3 - 5.2.12.Final - 1.4.193 - 42.2.2 - 6.4.0.jre8 - 2.3.0 - 6.0.6 - 8.6.0 - 2.5.8 - 1.3 - 2.1.4 - 1.5.0.10 - 6.5.0 - 10.11.1.1 - 1.8.0 - 2.10.0 - 1.23 - 3.0.0-M3 - 0.9.11 - 28.1-jre - 1.72 - 3.0.0-M3 - 1.8 - 1.4.0 - 7.1.1 - 2.3.2 - 7.0 - 2.3.1 - 1.1.3 - 1.2.0 - 9.4.20.v20190813 - 3.6.2 - 3.1.0 - 2.7.2 - 2.12.0 - - - - - - - - javax.xml.soap - javax.xml.soap-api - ${javax.xml.soap.version} - - - javax.xml.ws - jaxws-api - ${jaxws-api.version} - - - org.apache.geronimo.specs - geronimo-ws-metadata_2.0_spec - ${geronimo-ws-metadata_2.0_spec.version} - - - com.sun.activation - javax.activation - ${activation.version} - - - - - org.springframework.boot - spring-boot-dependencies - ${spring.boot.version} - pom - import - - - org.springframework.boot - spring-boot-starter-test - ${spring.boot.version} - - - org.ow2.asm - asm - - - - - - - org.reflections - reflections - ${reflections.version} - - - com.google.guava - guava - - - - - - - org.apache.wicket - wicket-core - ${wicket.version} - - - org.apache.wicket - wicket-request - ${wicket.version} - - - org.apache.wicket - wicket-ioc - ${wicket.version} - - - org.ow2.asm - asm - - - org.apache.ant - ant - - - - - org.apache.wicket - wicket-util - ${wicket.version} - - - org.apache.wicket - wicket-devutils - ${wicket.version} - - - org.apache.wicket - wicket-auth-roles - ${wicket.version} - - - org.apache.wicket - wicket-spring - ${wicket.version} - - - org.springframework - * - - - - - org.apache.wicket - wicket-extensions - ${wicket.version} - - - org.apache.wicket - wicket-datetime - 8.0.0-M7 - - - org.ow2.asm - asm - ${asm.version} - - - org.apache.commons - commons-email - ${commons-email.version} - - - javax.activation - activation - - - - - org.codehaus.groovy - groovy-all - ${groovy.version} - pom - - - org.codehaus.groovy - groovy-ant - - - org.codehaus.groovy - groovy-test-junit5 - - - org.codehaus.groovy - groovy-test - - - org.codehaus.groovy - groovy-testng - - - - - org.codehaus.groovy - groovy - ${groovy.version} - - - org.python - jython - 2.5.3 - - - com.h2database - h2 - ${h2.version} - - - org.hibernate - hibernate-core - ${hibernate.version} - - - javax.annotation - jsr250-api - - - - - org.hibernate.javax.persistence - hibernate-jpa-2.1-api - 1.0.0.Final - - - org.javassist - javassist - - 3.25.0-GA - - - com.zaxxer - HikariCP - 3.3.1 - - - org.slf4j - jul-to-slf4j - ${slf4j.version} - - - ch.qos.logback - logback-classic - ${logback.version} - - - ch.qos.logback - logback-core - ${logback.version} - - - org.codehaus.janino - janino - 3.0.10 - - - com.sleepycat - je - 5.0.103 - - - - xerces - xercesImpl - ${xerces.version} - - - xalan - xalan - ${xalan.version} - - - org.codehaus.staxmate - staxmate - 2.0.1 - - - stax - stax-api - - - - - javax.xml.bind - jaxb-api - ${jaxb-api.version} - - - com.sun.xml.bind - jaxb-impl - ${jaxb.version} - - - com.sun.xml.bind - jaxb-core - ${jaxb.version} - - - com.sun.xml.bind - jaxb-xjc - ${jaxb-xjc.version} - - - net.sourceforge.ccxjc - cc-xjc-plugin - 2.0 - - - com.sun.xsom - xsom - 20140925 - - - commons-validator - commons-validator - 1.5.1 - - - - commons-logging - commons-logging - - - commons-digester - commons-digester - - - - - commons-beanutils - commons-beanutils - 1.9.4 - - - - commons-logging - commons-logging - - - - - commons-codec - commons-codec - 1.10 - - - commons-collections - commons-collections - 3.2.2 - - - org.apache.commons - commons-configuration2 - 2.6 - - - - commons-logging - commons-logging - - - - - org.apache.commons - commons-text - 1.8 - - - - com.google.code.findbugs - jsr305 - 3.0.2 - - - commons-io - commons-io - ${commons.io.version} - - - commons-lang - commons-lang - ${commons.lang.version} - - - org.apache.commons - commons-lang3 - ${commons.lang3.version} - - - commons-pool - commons-pool - 1.5.6 - - - commons-javaflow - commons-javaflow - 20060411 - - - org.jetbrains - annotations - 18.0.0 - - - javax.annotation - jsr250-api - 1.0 - - - javax.jws - jsr181-api - 1.0-MR1 - - - javax.inject - javax.inject - 1 - - - javax.persistence - persistence-api - 1.0 - true - - - javax.servlet - servlet-api - 2.5 - provided - - - javax.ws.rs - javax.ws.rs-api - 2.1 - - - - org.apache.httpcomponents - httpclient - 4.5.3.e3 - - - - commons-logging - commons-logging - - - - - - org.apache.httpcomponents - httpcore - 4.4.6 - - - org.apache.cxf - cxf-rt-core - ${cxf.version} - - - - org.apache.geronimo.specs - geronimo-javamail_1.4_spec - - - org.apache.geronimo.specs - geronimo-activation_1.1_spec - - - javax.activation - activation - - - - - org.apache.cxf - cxf-core - ${cxf.version} - - - org.jvnet.staxex - stax-ex - - - javax.xml.soap - javax.xml.soap-api - - - - org.glassfish.jaxb - jaxb-xjc - - - - - org.apache.cxf - cxf-rt-frontend-simple - ${cxf.version} - - - org.apache.cxf - cxf-rt-wsdl - ${cxf.version} - - - javax.activation - activation - - - - - org.apache.cxf - cxf-tools-common - ${cxf.version} - - - org.jvnet.staxex - stax-ex - - - javax.xml.soap - javax.xml.soap-api - - - - - org.apache.cxf - cxf-rt-frontend-jaxws - ${cxf.version} - - - org.apache.cxf - cxf-rt-databinding-aegis - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-local - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-http - ${cxf.version} - - - - org.apache.httpcomponents - httpclient - - - - org.apache.httpcomponents - httpcore - - - - - org.apache.cxf - cxf-rt-transports-http-jetty - ${cxf.version} - - - org.apache.cxf - cxf-rt-transports-jms - ${cxf.version} - - - org.apache.cxf - cxf-rt-management - ${cxf.version} - - - org.apache.cxf - cxf-rt-bindings-soap - ${cxf.version} - - - org.apache.cxf - cxf-rt-ws-security - ${cxf.version} - - - org.codehaus.woodstox - woodstox-core-asl - - - - - org.apache.cxf - cxf-rt-frontend-jaxrs - ${cxf.version} - - - jakarta.ws.rs - jakarta.ws.rs-api - - - - - org.apache.cxf - cxf-rt-rs-client - ${cxf.version} - - - org.jvnet.staxex - stax-ex - - - javax.xml.soap - javax.xml.soap-api - - - - - org.apache.cxf - cxf-rt-rs-extension-providers - ${cxf.version} - - - org.apache.cxf.xjc-utils - cxf-xjc-runtime - ${cxf-xjc.version} - - - javax.activation - activation - - - - - org.apache.wss4j - wss4j-ws-security-common - ${wss4j.version} - - - org.apache.geronimo.javamail - geronimo-javamail_1.4_mail - - - org.bouncycastle - bcprov-jdk15on - - - com.google.guava - guava - - - - - com.google.guava - guava - ${guava.version} - - - org.apache.wss4j - wss4j-ws-security-dom - ${wss4j.version} - - - org.bouncycastle - bcprov-jdk15on - - - - - - org.codehaus.woodstox - stax2-api - 3.1.4 - - - org.apache.felix - org.osgi.core - 1.4.0 - - - org.forgerock.opendj - opendj - ${opendj.version} - - - - net.tirasa.connid - connector-framework - ${connid.version} - - - net.tirasa.connid - connector-framework-internal - ${connid.version} - - - com.evolveum.polygon - connector-databasetable - 1.4.3.0 - - - com.evolveum.polygon - connector-csv - 2.3 - - - com.evolveum.polygon - connector-ldap - 3.0-M1 - - - - org.slf4j - slf4j-jdk14 - - - - - - com.evolveum.icf - dummy - 1.1.0.0-e1 - - - org.scannotation - scannotation - 1.0.3 - - - - org.slf4j - jcl-over-slf4j - ${slf4j.version} - - - org.slf4j - log4j-over-slf4j - ${slf4j.version} - - - org.slf4j - slf4j-api - ${slf4j.version} - - - org.quartz-scheduler - quartz - ${quartz.version} - - - com.mchange - c3p0 - - - com.mchange - mchange-commons-java - - - com.zaxxer - * - - - - - - org.apache.santuario - xmlsec - ${xmlsec.version} - - - javax.xml.stream - stax-api - - - org.codehaus.woodstox - woodstox-core-asl - - - - - org.springframework - spring-core - ${spring.version} - - - - org.springframework - spring-jcl - - - - - org.springframework.security.extensions - spring-security-saml2-core - ${spring.security.saml2.version} - - - commons-logging - commons-logging - - - org.bouncycastle - bcpkix-jdk15on - - - org.bouncycastle - bcprov-jdk15on - - - - - org.cache2k - cache2k-api - ${cache2k.version} - - - org.cache2k - cache2k-core - ${cache2k.version} - - - aopalliance - aopalliance - 1.0 - - - - org.xmlunit - xmlunit-core - ${xmlunit.version} - - - org.xmlunit - xmlunit-legacy - ${xmlunit.version} - - - xml-resolver - xml-resolver - ${xml.resolver.version} - - - mysql - mysql-connector-java - ${jdbc.mysql} - - - org.postgresql - postgresql - ${jdbc.postgres} - - - com.microsoft.sqlserver - mssql-jdbc - ${jdbc.sqlserver} - - - org.mariadb.jdbc - mariadb-java-client - ${jdbc.mariadb} - - - commons-cli - commons-cli - ${commons.cli} - - - org.forgerock.opendj - opendj-ldap-sdk - ${opendj.version} - - - org.apache.velocity - velocity - 1.7 - - - org.apache.derby - derby - ${derby.version} - - - org.apache.derby - derbynet - ${derby.version} - - - org.apache.derby - derbyclient - ${derby.version} - - - - - net.sf.jasperreports - jasperreports - ${jasper.version} - - - xml-apis - xml-apis - - - com.fasterxml.jackson.core - jackson-core - - - com.fasterxml.jackson.core - jackson-databind - - - com.fasterxml.jackson.core - jackson-annotations - - - - commons-logging - commons-logging - - - bouncycastle - bcmail-jdk14 - - - org.bouncycastle - bcmail-jdk14 - - - bouncycastle - bcprov-jdk14 - - - org.bouncycastle - bcprov-jdk14 - - - org.bouncycastle - bctsp-jdk14 - - - - javax.xml.stream - stax-api - - - - - - stax - stax - 1.2.0 - - - stax - stax-api - - - - - - - org.apache.poi - poi - 3.17 - - - com.fasterxml.jackson.core - jackson-core - ${jackson.version} - - - com.fasterxml.jackson.core - jackson-annotations - ${jackson.version} - - - com.fasterxml.jackson.jaxrs - jackson-jaxrs-base - ${jackson.version} - - - org.yaml - snakeyaml - ${snakeyaml.version} - - - com.fasterxml.jackson.core - jackson-databind - ${jackson.version} - - - com.fasterxml.jackson.module - jackson-module-jaxb-annotations - ${jackson.version} - - - com.fasterxml.jackson.dataformat - jackson-dataformat-yaml - ${jackson.version} - - - org.apache.ws.xmlschema - xmlschema-core - 2.1.0 - - - org.jvnet.jaxb2_commons - jaxb2-basics-runtime - 0.6.3 - - - - - org.apache.maven - maven-plugin-api - ${maven.api.version} - - - org.codehaus.plexus - plexus-component-annotations - - - org.codehaus.plexus - plexus-classworlds - - - - - org.apache.maven - maven-model - ${maven.api.version} - - - org.apache.maven - maven-artifact - ${maven.api.version} - - - org.apache.maven - maven-core - ${maven.api.version} - - - org.apache.maven - maven-archiver - 3.4.0 - - - org.codehaus.plexus - plexus-container-default - - - org.codehaus.plexus - plexus-component-annotations - - - org.slf4j - slf4j-jdk14 - - - - - org.codehaus.plexus - plexus-archiver - 4.1.0 - - - org.slf4j - slf4j-jdk14 - - - - - org.codehaus.plexus - plexus-utils - 3.1.0 - - - org.codehaus.plexus - plexus-io - 3.1.1 - - - org.codehaus.plexus - plexus-interactivity-api - 1.0 - - - org.codehaus.plexus - plexus-classworlds - - - - - - ro.isdc.wro4j - wro4j-core - ${wro4j.version} - - - slf4j-api - org.slf4j - - - org.webjars - webjars-locator - - - - - ro.isdc.wro4j - wro4j-extensions - ${wro4j.version} - - - org.slf4j - slf4j-api - - - org.slf4j - slf4j-log4j12 - - - - - joda-time - joda-time - 2.6 - - - org.apache.commons - commons-collections4 - 4.1 - - - org.apache.directory.api - api-all - 1.0.0 - - - slf4j-api - org.slf4j - - - xml-apis - xml-apis - - - - - javax.mail - mail - 1.4.5 - - - javax.mail - javax.mail-api - 1.5.4 - - - org.ocpsoft.prettytime - prettytime - 4.0.0.Final - - - com.github.openjson - openjson - 1.0.10 - - - org.opensaml - opensaml-security-impl - 3.3.0 - - - - - org.webjars.bower - adminlte - 2.3.11 - - - org.webjars - respond - 1.4.2 - - - org.webjars - html5shiv - 3.7.3 - - - org.webjars - font-awesome - 4.7.0 - - - org.webjars.npm - ionicons - 3.0.0 - - - org.webjars - webjars-locator-core - 0.35 - - - org.webjars - less - 2.5.3 - - - org.webjars - swagger-ui - 2.2.5 - - - - com.beust - jcommander - ${jcommander.version} - - - - org.eclipse.jetty - jetty-server - ${jetty.version} - - - org.eclipse.jetty - jetty-http - ${jetty.version} - - - org.eclipse.jetty - jetty-io - ${jetty.version} - - - org.eclipse.jetty - jetty-util - ${jetty.version} - - - org.apache.qpid - qpid-broker-core - ${qpid-broker.version} - - - org.apache.qpid - qpid-broker-plugins-amqp-0-8-protocol - ${qpid-broker.version} - - - org.apache.qpid - qpid-broker-plugins-memory-store - ${qpid-broker.version} - - - - org.jasig.cas.client - cas-client-core - 3.5.1 - - - - - com.codeborne - selenide - 5.3.1 - - - - io.netty - netty-all - - - com.google.guava - guava - - - - - org.seleniumhq.selenium - selenium-java - 3.14.0 - - - - commons-logging - commons-logging - - - - - org.seleniumhq.selenium - selenium-api - ${selenium.version} - - - - com.squareup.okio - okio - 1.14.1 - - - io.netty - netty-all - 4.1.42.Final - - - ch.qos.logback - * - - - - - org.jsoup - jsoup - 1.10.2 - - - dnsjava - dnsjava - 2.1.8 - - - - - org.testng - testng - ${testng.version} - - - com.evolveum.midpoint.tools - test-ng - ${project.version} - - - com.evolveum.midpoint.infra - test-util - ${project.version} - - - - - - - - - evolveum - Evolveum Public Releases - https://nexus.evolveum.com/nexus/content/groups/public/ - - - evolveum-snapshots - Evolveum Snapshots - https://nexus.evolveum.com/nexus/content/repositories/snapshots/ - - - spring-milestone - Spring Milestone Repository - https://repo.spring.io/milestone - - - - - evolveum - Evolveum - https://nexus.evolveum.com/nexus/content/groups/public - - - - - - - org.springframework.boot - spring-boot-maven-plugin - 2.0.1.RELEASE - - true - - - - - org.apache.maven.plugins - maven-source-plugin - 3.1.0 - - - attach-sources - package - - jar - - - - - - com.lukegb.mojo - gitdescribe-maven-plugin - 3.0 - - - - gitdescribe - - git-describe - initialize - - - - - - - - org.apache.maven.plugins - maven-jar-plugin - 3.2.0 - - true - - - ${project.version} - ${git.describe} - Evolveum - https://www.evolveum.com - https://jira.evolveum.com - dual-licensed under the Apache License 2.0 and European Union Public License - https://www.apache.org/licenses/LICENSE-2.0.txt and https://joinup.ec.europa.eu/collection/eupl/eupl-text-11-12 - - - - - - org.apache.maven.plugins - maven-war-plugin - 3.2.3 - - - - ${project.version} - ${git.describe} - Evolveum - https://www.evolveum.com - https://jira.evolveum.com - dual-licensed under the Apache License 2.0 and European Union Public License - https://www.apache.org/licenses/LICENSE-2.0.txt and https://joinup.ec.europa.eu/collection/eupl/eupl-text-11-12 - - - true - false - - - - org.eclipse.jetty - jetty-maven-plugin - ${jetty.version} - - - - org.eclipse.jetty.annotations.maxWait - 240 - - - - /midpoint - - - true - - -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n - - - - - pl.project13.maven - git-commit-id-plugin - 3.0.1 - - - - org.apache.maven.plugins - maven-shade-plugin - 2.3 - - - org.apache.maven.plugins - maven-enforcer-plugin - 3.0.0-M2 - - - enforce - - - - 3.6 - - - - - - commons-logging:commons-logging - org.springframework:spring-jcl - - - - - - - - enforce - - - - - - - org.apache.maven.plugins - maven-dependency-plugin - 3.1.1e1 - - - analyze - - analyze-only - - - true - true - - - - - - javax.xml.bind:jaxb-api - com.sun.activation:javax.activation - javax.activation:activation - - - xml-apis:xml-apis - - - jakarta.activation:jakarta.activation-api - jakarta.xml.bind:jakarta.xml.bind-api - org.glassfish.jaxb:xsom - org.glassfish.jaxb:jaxb-runtime - - - org.slf4j:jcl-over-slf4j - org.slf4j:slf4j-api - org.danekja:jdk-serializable-functional - - - - - - - maven-javadoc-plugin - 3.1.1 - - - org.apache.maven.plugins - maven-checkstyle-plugin - ${checkstyle.version} - - ${maven.multiModuleProjectDirectory}/config/checkstyle/checkstyle.xml - ${maven.multiModuleProjectDirectory}/config/checkstyle/checkstyle-suppressions.xml - UTF-8 - true - true - false - **/*.java - - **/*.properties,**/*.xml,**/*.xsd,**/*.wsdl,**/*.json,**/*.yaml,**/*.yml - - - - validate - validate - - check - - - - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.8.0 - - ${project.source.version} - ${project.source.version} - - - - org.apache.maven.plugins - maven-resources-plugin - 3.1.0 - - - com.rimerosolutions.maven.plugins - wrapper-maven-plugin - 0.0.4 - - - org.apache.maven.plugins - maven-plugin-plugin - - 3.6.0 - - - org.apache.maven.plugins - maven-deploy-plugin - 2.8.2 - - - org.eclipse.m2e - lifecycle-mapping - 1.0.0 - - - - - - org.apache.maven.plugins - maven-dependency-plugin - [3.1.1,) - - copy-dependencies - unpack - - - - - - - - - org.apache.cxf - cxf-codegen-plugin - [3.3.1,) - - wsdl2java - - - - - - - - - com.lukegb.mojo - gitdescribe-maven-plugin - [3.0,) - - gitdescribe - - - - - - - - - - - - org.apache.maven.plugins - maven-surefire-plugin - ${surefire.version} - - - default-test - test - - test - - - - - false - 1 - true - ${redirectTestOutputToFile} - false - - false - - src/test/resources/truststore.jks - target/midpoint-home - ${project.build.directory}/test-classes/logging.properties - - - ${surefire.args} - - - - /opt/jenkins_db_configs/ojdbc7.jar - - c:\midpoint\jdbc-drivers\ojdbc7.jar - - - testng-unit.xml - - - - suitename - Unit - - - listener - - com.evolveum.midpoint.tools.testng.TestListener,com.evolveum.midpoint.tools.testng.RetryListener - - - - - - - org.apache.maven.surefire - surefire-testng - ${surefire.version} - - - - - org.apache.maven.plugins - maven-failsafe-plugin - ${failsafe.version} - - - integration-test - integration-test - - integration-test - verify - - - - - ${redirectTestOutputToFile} - - src/test/resources/truststore.jks - target/midpoint-home - ${project.build.directory}/test-classes/logging.properties - - ${failsafe.args} - - testng-integration.xml - - - - suitename - Integration - - - listener - com.evolveum.midpoint.tools.testng.TestListener,com.evolveum.midpoint.tools.testng.RetryListener - - - - - /opt/jenkins_db_configs/ojdbc7.jar - - c:\midpoint\jdbc-drivers\ojdbc7.jar - - - - - - org.codehaus.mojo - findbugs-maven-plugin - 3.0.5 - - Max - Low - true - com.evolveum.midpoint.* - - - - maven-assembly-plugin - 3.1.1 - - - - - - - - - org.codehaus.mojo - findbugs-maven-plugin - - - org.apache.maven.plugins - maven-checkstyle-plugin - - ${checkstyle.version} - - ${maven.multiModuleProjectDirectory}/build-system/checkstyle-configs/checkstyle.xml - - UTF-8 - true - true - false - - - - - checkstyle - - - - - - - - - - dist - - - !skipDist - - - - dist - - - - - - extratest - - true - - - - - jdk-11 - - 11 - - - 11 - - - - - - xerces - xercesImpl - ${xerces.version} - - - xml-apis - xml-apis - - - - - xalan - serializer - ${xalan.version} - - - xml-apis - xml-apis - - - - - - - - - jdk-8 - - 1.8 - - - 1.8 - - - - + + + + + 4.0.0 + + + + com.evolveum.midpoint + midpoint + 4.1-SNAPSHOT + pom + + midPoint Project + Utility module to compile all of the maven based midPoint projects. + + evolveum + https://www.evolveum.com + + + + Apache License v2.0 + https://www.apache.org/licenses/LICENSE-2.0.txt + repo + + + European Union Public License + https://joinup.ec.europa.eu/collection/eupl/eupl-text-11-12 + repo + + + + + tools + infra + repo + provisioning + model + custom + gui + icf-connectors + testing + + + + https://github.com/Evolveum/midpoint.git + git@github.com:Evolveum/midpoint.git + https://github.com/Evolveum/midpoint.git + + + Atlassian JIRA + https://jira.evolveum.com/browse/MID + + + + evolveum-nexus + Internal Releases + https://nexus.evolveum.com/nexus/content/repositories/releases/ + + + evolveum-nexus + Internal Snapshots + https://nexus.evolveum.com/nexus/content/repositories/snapshots/ + + + + + + + UTF-8 + 1.8 + en_US + true + false + false + + + ${describe} + ${maven.build.timestamp} + EEE, d MMM yyyy HH:mm:ss Z + + + -Xms1024m -Xmx4096m + -Xms1024m -Xmx4096m -Duser.language=en + + full + + true + + + 2.6 + 2.6 + 3.7 + 1.2 + 3.3.1 + 3.3.0 + 2.2.0 + 2.4.7 + 2.3.1 + 2.3.0.1 + 2.3.0.1 + 2.6.2 + 2.3.0.e3 + 3.141.59 + 1.7.25 + 1.2.3 + 2.1.8.RELEASE + + 5.1.9.RELEASE + 5.1.6.RELEASE + 2.0.0.M30 + 1.2.1.Final + 3.5.0 + 6.14.3 + 1.2 + 2.1.1 + 2.2.3 + 5.2.12.Final + 1.4.193 + 42.2.2 + 6.4.0.jre8 + 2.3.0 + 6.0.6 + 8.6.0 + 2.5.8 + 1.3 + 2.1.4 + 1.5.0.10 + 6.5.0 + 10.11.1.1 + 1.8.0 + 2.10.0 + 1.23 + 3.0.0-M3 + 0.9.11 + 28.1-jre + 1.72 + 3.0.0-M3 + 1.8 + 1.4.0 + 7.1.1 + 2.3.2 + 7.0 + 2.3.1 + 1.1.3 + 1.2.0 + 9.4.20.v20190813 + 3.6.2 + 3.1.0 + 2.7.2 + 2.12.0 + + + + + + + + javax.xml.soap + javax.xml.soap-api + ${javax.xml.soap.version} + + + javax.xml.ws + jaxws-api + ${jaxws-api.version} + + + org.apache.geronimo.specs + geronimo-ws-metadata_2.0_spec + ${geronimo-ws-metadata_2.0_spec.version} + + + com.sun.activation + javax.activation + ${activation.version} + + + + + org.springframework.boot + spring-boot-dependencies + ${spring.boot.version} + pom + import + + + org.springframework.boot + spring-boot-starter-test + ${spring.boot.version} + + + org.ow2.asm + asm + + + + + + + org.reflections + reflections + ${reflections.version} + + + com.google.guava + guava + + + + + + + org.apache.wicket + wicket-core + ${wicket.version} + + + org.apache.wicket + wicket-request + ${wicket.version} + + + org.apache.wicket + wicket-ioc + ${wicket.version} + + + org.ow2.asm + asm + + + org.apache.ant + ant + + + + + org.apache.wicket + wicket-util + ${wicket.version} + + + org.apache.wicket + wicket-devutils + ${wicket.version} + + + org.apache.wicket + wicket-auth-roles + ${wicket.version} + + + org.apache.wicket + wicket-spring + ${wicket.version} + + + org.springframework + * + + + + + org.apache.wicket + wicket-extensions + ${wicket.version} + + + org.apache.wicket + wicket-datetime + 8.0.0-M7 + + + org.ow2.asm + asm + ${asm.version} + + + org.apache.commons + commons-email + ${commons-email.version} + + + javax.activation + activation + + + + + org.codehaus.groovy + groovy-all + ${groovy.version} + pom + + + org.codehaus.groovy + groovy-ant + + + org.codehaus.groovy + groovy-test-junit5 + + + org.codehaus.groovy + groovy-test + + + org.codehaus.groovy + groovy-testng + + + + + org.codehaus.groovy + groovy + ${groovy.version} + + + org.python + jython + 2.5.3 + + + com.h2database + h2 + ${h2.version} + + + org.hibernate + hibernate-core + ${hibernate.version} + + + javax.annotation + jsr250-api + + + + + org.hibernate.javax.persistence + hibernate-jpa-2.1-api + 1.0.0.Final + + + org.javassist + javassist + + 3.25.0-GA + + + com.zaxxer + HikariCP + 3.3.1 + + + org.slf4j + jul-to-slf4j + ${slf4j.version} + + + ch.qos.logback + logback-classic + ${logback.version} + + + ch.qos.logback + logback-core + ${logback.version} + + + org.codehaus.janino + janino + 3.0.10 + + + com.sleepycat + je + 5.0.103 + + + + xerces + xercesImpl + ${xerces.version} + + + xalan + xalan + ${xalan.version} + + + org.codehaus.staxmate + staxmate + 2.0.1 + + + stax + stax-api + + + + + javax.xml.bind + jaxb-api + ${jaxb-api.version} + + + com.sun.xml.bind + jaxb-impl + ${jaxb.version} + + + com.sun.xml.bind + jaxb-core + ${jaxb.version} + + + com.sun.xml.bind + jaxb-xjc + ${jaxb-xjc.version} + + + net.sourceforge.ccxjc + cc-xjc-plugin + 2.0 + + + com.sun.xsom + xsom + 20140925 + + + commons-validator + commons-validator + 1.5.1 + + + + commons-logging + commons-logging + + + commons-digester + commons-digester + + + + + commons-beanutils + commons-beanutils + 1.9.4 + + + + commons-logging + commons-logging + + + + + commons-codec + commons-codec + 1.10 + + + commons-collections + commons-collections + 3.2.2 + + + org.apache.commons + commons-configuration2 + 2.6 + + + + commons-logging + commons-logging + + + + + org.apache.commons + commons-text + 1.8 + + + + com.google.code.findbugs + jsr305 + 3.0.2 + + + commons-io + commons-io + ${commons.io.version} + + + commons-lang + commons-lang + ${commons.lang.version} + + + org.apache.commons + commons-lang3 + ${commons.lang3.version} + + + commons-pool + commons-pool + 1.5.6 + + + commons-javaflow + commons-javaflow + 20060411 + + + org.jetbrains + annotations + 18.0.0 + + + javax.annotation + jsr250-api + 1.0 + + + javax.jws + jsr181-api + 1.0-MR1 + + + javax.inject + javax.inject + 1 + + + javax.persistence + persistence-api + 1.0 + true + + + javax.servlet + servlet-api + 2.5 + provided + + + javax.ws.rs + javax.ws.rs-api + 2.1 + + + + org.apache.httpcomponents + httpclient + 4.5.3.e3 + + + + commons-logging + commons-logging + + + + + + org.apache.httpcomponents + httpcore + 4.4.6 + + + org.apache.cxf + cxf-rt-core + ${cxf.version} + + + + org.apache.geronimo.specs + geronimo-javamail_1.4_spec + + + org.apache.geronimo.specs + geronimo-activation_1.1_spec + + + javax.activation + activation + + + + + org.apache.cxf + cxf-core + ${cxf.version} + + + org.jvnet.staxex + stax-ex + + + javax.xml.soap + javax.xml.soap-api + + + + org.glassfish.jaxb + jaxb-xjc + + + + + org.apache.cxf + cxf-rt-frontend-simple + ${cxf.version} + + + org.apache.cxf + cxf-rt-wsdl + ${cxf.version} + + + javax.activation + activation + + + + + org.apache.cxf + cxf-tools-common + ${cxf.version} + + + org.jvnet.staxex + stax-ex + + + javax.xml.soap + javax.xml.soap-api + + + + + org.apache.cxf + cxf-rt-frontend-jaxws + ${cxf.version} + + + org.apache.cxf + cxf-rt-databinding-aegis + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-local + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-http + ${cxf.version} + + + + org.apache.httpcomponents + httpclient + + + + org.apache.httpcomponents + httpcore + + + + + org.apache.cxf + cxf-rt-transports-http-jetty + ${cxf.version} + + + org.apache.cxf + cxf-rt-transports-jms + ${cxf.version} + + + org.apache.cxf + cxf-rt-management + ${cxf.version} + + + org.apache.cxf + cxf-rt-bindings-soap + ${cxf.version} + + + org.apache.cxf + cxf-rt-ws-security + ${cxf.version} + + + org.codehaus.woodstox + woodstox-core-asl + + + + + org.apache.cxf + cxf-rt-frontend-jaxrs + ${cxf.version} + + + jakarta.ws.rs + jakarta.ws.rs-api + + + + + org.apache.cxf + cxf-rt-rs-client + ${cxf.version} + + + org.jvnet.staxex + stax-ex + + + javax.xml.soap + javax.xml.soap-api + + + + + org.apache.cxf + cxf-rt-rs-extension-providers + ${cxf.version} + + + org.apache.cxf.xjc-utils + cxf-xjc-runtime + ${cxf-xjc.version} + + + javax.activation + activation + + + + + org.apache.wss4j + wss4j-ws-security-common + ${wss4j.version} + + + org.apache.geronimo.javamail + geronimo-javamail_1.4_mail + + + org.bouncycastle + bcprov-jdk15on + + + com.google.guava + guava + + + + + com.google.guava + guava + ${guava.version} + + + org.apache.wss4j + wss4j-ws-security-dom + ${wss4j.version} + + + org.bouncycastle + bcprov-jdk15on + + + + + + org.codehaus.woodstox + stax2-api + 3.1.4 + + + org.apache.felix + org.osgi.core + 1.4.0 + + + org.forgerock.opendj + opendj + ${opendj.version} + + + + net.tirasa.connid + connector-framework + ${connid.version} + + + net.tirasa.connid + connector-framework-internal + ${connid.version} + + + com.evolveum.polygon + connector-databasetable + 1.4.3.0 + + + com.evolveum.polygon + connector-csv + 2.3 + + + com.evolveum.polygon + connector-ldap + 3.0-SNAPSHOT + + + + org.slf4j + slf4j-jdk14 + + + + + com.evolveum.polygon + connector-powershell + 1.0-M1 + + + + com.evolveum.icf + dummy + 1.1.0.0-e1 + + + org.scannotation + scannotation + 1.0.3 + + + + org.slf4j + jcl-over-slf4j + ${slf4j.version} + + + org.slf4j + log4j-over-slf4j + ${slf4j.version} + + + org.slf4j + slf4j-api + ${slf4j.version} + + + org.quartz-scheduler + quartz + ${quartz.version} + + + com.mchange + c3p0 + + + com.mchange + mchange-commons-java + + + com.zaxxer + * + + + + + + org.apache.santuario + xmlsec + ${xmlsec.version} + + + javax.xml.stream + stax-api + + + org.codehaus.woodstox + woodstox-core-asl + + + + + org.springframework + spring-core + ${spring.version} + + + + org.springframework + spring-jcl + + + + + org.springframework.security.extensions + spring-security-saml2-core + ${spring.security.saml2.version} + + + commons-logging + commons-logging + + + org.bouncycastle + bcpkix-jdk15on + + + org.bouncycastle + bcprov-jdk15on + + + + + org.cache2k + cache2k-api + ${cache2k.version} + + + org.cache2k + cache2k-core + ${cache2k.version} + + + aopalliance + aopalliance + 1.0 + + + + org.xmlunit + xmlunit-core + ${xmlunit.version} + + + org.xmlunit + xmlunit-legacy + ${xmlunit.version} + + + xml-resolver + xml-resolver + ${xml.resolver.version} + + + mysql + mysql-connector-java + ${jdbc.mysql} + + + org.postgresql + postgresql + ${jdbc.postgres} + + + com.microsoft.sqlserver + mssql-jdbc + ${jdbc.sqlserver} + + + org.mariadb.jdbc + mariadb-java-client + ${jdbc.mariadb} + + + commons-cli + commons-cli + ${commons.cli} + + + org.forgerock.opendj + opendj-ldap-sdk + ${opendj.version} + + + org.apache.velocity + velocity + 1.7 + + + org.apache.derby + derby + ${derby.version} + + + org.apache.derby + derbynet + ${derby.version} + + + org.apache.derby + derbyclient + ${derby.version} + + + + + net.sf.jasperreports + jasperreports + ${jasper.version} + + + xml-apis + xml-apis + + + com.fasterxml.jackson.core + jackson-core + + + com.fasterxml.jackson.core + jackson-databind + + + com.fasterxml.jackson.core + jackson-annotations + + + + commons-logging + commons-logging + + + bouncycastle + bcmail-jdk14 + + + org.bouncycastle + bcmail-jdk14 + + + bouncycastle + bcprov-jdk14 + + + org.bouncycastle + bcprov-jdk14 + + + org.bouncycastle + bctsp-jdk14 + + + + javax.xml.stream + stax-api + + + + + + stax + stax + 1.2.0 + + + stax + stax-api + + + + + + + org.apache.poi + poi + 3.17 + + + com.fasterxml.jackson.core + jackson-core + ${jackson.version} + + + com.fasterxml.jackson.core + jackson-annotations + ${jackson.version} + + + com.fasterxml.jackson.jaxrs + jackson-jaxrs-base + ${jackson.version} + + + org.yaml + snakeyaml + ${snakeyaml.version} + + + com.fasterxml.jackson.core + jackson-databind + ${jackson.version} + + + com.fasterxml.jackson.module + jackson-module-jaxb-annotations + ${jackson.version} + + + com.fasterxml.jackson.dataformat + jackson-dataformat-yaml + ${jackson.version} + + + org.apache.ws.xmlschema + xmlschema-core + 2.1.0 + + + org.jvnet.jaxb2_commons + jaxb2-basics-runtime + 0.6.3 + + + + + org.apache.maven + maven-plugin-api + ${maven.api.version} + + + org.codehaus.plexus + plexus-component-annotations + + + org.codehaus.plexus + plexus-classworlds + + + + + org.apache.maven + maven-model + ${maven.api.version} + + + org.apache.maven + maven-artifact + ${maven.api.version} + + + org.apache.maven + maven-core + ${maven.api.version} + + + org.apache.maven + maven-archiver + 3.4.0 + + + org.codehaus.plexus + plexus-container-default + + + org.codehaus.plexus + plexus-component-annotations + + + org.slf4j + slf4j-jdk14 + + + + + org.codehaus.plexus + plexus-archiver + 4.1.0 + + + org.slf4j + slf4j-jdk14 + + + + + org.codehaus.plexus + plexus-utils + 3.1.0 + + + org.codehaus.plexus + plexus-io + 3.1.1 + + + org.codehaus.plexus + plexus-interactivity-api + 1.0 + + + org.codehaus.plexus + plexus-classworlds + + + + + + ro.isdc.wro4j + wro4j-core + ${wro4j.version} + + + slf4j-api + org.slf4j + + + org.webjars + webjars-locator + + + + + ro.isdc.wro4j + wro4j-extensions + ${wro4j.version} + + + org.slf4j + slf4j-api + + + org.slf4j + slf4j-log4j12 + + + + + joda-time + joda-time + 2.6 + + + org.apache.commons + commons-collections4 + 4.1 + + + org.apache.directory.api + api-all + 1.0.0 + + + slf4j-api + org.slf4j + + + xml-apis + xml-apis + + + + + javax.mail + mail + 1.4.5 + + + javax.mail + javax.mail-api + 1.5.4 + + + org.ocpsoft.prettytime + prettytime + 4.0.0.Final + + + com.github.openjson + openjson + 1.0.10 + + + org.opensaml + opensaml-security-impl + 3.3.0 + + + + + org.webjars.bower + adminlte + 2.3.11 + + + org.webjars + respond + 1.4.2 + + + org.webjars + html5shiv + 3.7.3 + + + org.webjars + font-awesome + 4.7.0 + + + org.webjars.npm + ionicons + 3.0.0 + + + org.webjars + webjars-locator-core + 0.35 + + + org.webjars + less + 2.5.3 + + + org.webjars + swagger-ui + 2.2.5 + + + + com.beust + jcommander + ${jcommander.version} + + + + org.eclipse.jetty + jetty-server + ${jetty.version} + + + org.eclipse.jetty + jetty-http + ${jetty.version} + + + org.eclipse.jetty + jetty-io + ${jetty.version} + + + org.eclipse.jetty + jetty-util + ${jetty.version} + + + org.apache.qpid + qpid-broker-core + ${qpid-broker.version} + + + org.apache.qpid + qpid-broker-plugins-amqp-0-8-protocol + ${qpid-broker.version} + + + org.apache.qpid + qpid-broker-plugins-memory-store + ${qpid-broker.version} + + + + org.jasig.cas.client + cas-client-core + 3.5.1 + + + + + com.codeborne + selenide + 5.3.1 + + + + io.netty + netty-all + + + com.google.guava + guava + + + + + org.seleniumhq.selenium + selenium-java + 3.14.0 + + + + commons-logging + commons-logging + + + + + org.seleniumhq.selenium + selenium-api + ${selenium.version} + + + + com.squareup.okio + okio + 1.14.1 + + + io.netty + netty-all + 4.1.42.Final + + + ch.qos.logback + * + + + + + org.jsoup + jsoup + 1.10.2 + + + dnsjava + dnsjava + 2.1.8 + + + + + org.testng + testng + ${testng.version} + + + com.evolveum.midpoint.tools + test-ng + ${project.version} + + + com.evolveum.midpoint.infra + test-util + ${project.version} + + + + + + + + + evolveum + Evolveum Public Releases + https://nexus.evolveum.com/nexus/content/groups/public/ + + + evolveum-snapshots + Evolveum Snapshots + https://nexus.evolveum.com/nexus/content/repositories/snapshots/ + + + spring-milestone + Spring Milestone Repository + https://repo.spring.io/milestone + + + + + evolveum + Evolveum + https://nexus.evolveum.com/nexus/content/groups/public + + + + + + + org.springframework.boot + spring-boot-maven-plugin + 2.0.1.RELEASE + + true + + + + + org.apache.maven.plugins + maven-source-plugin + 3.1.0 + + + attach-sources + package + + jar + + + + + + com.lukegb.mojo + gitdescribe-maven-plugin + 3.0 + + + + gitdescribe + + git-describe + initialize + + + + + + + + org.apache.maven.plugins + maven-jar-plugin + 3.2.0 + + true + + + ${project.version} + ${git.describe} + Evolveum + https://www.evolveum.com + https://jira.evolveum.com + dual-licensed under the Apache License 2.0 and European Union Public License + https://www.apache.org/licenses/LICENSE-2.0.txt and https://joinup.ec.europa.eu/collection/eupl/eupl-text-11-12 + + + + + + org.apache.maven.plugins + maven-war-plugin + 3.2.3 + + + + ${project.version} + ${git.describe} + Evolveum + https://www.evolveum.com + https://jira.evolveum.com + dual-licensed under the Apache License 2.0 and European Union Public License + https://www.apache.org/licenses/LICENSE-2.0.txt and https://joinup.ec.europa.eu/collection/eupl/eupl-text-11-12 + + + true + false + + + + org.eclipse.jetty + jetty-maven-plugin + ${jetty.version} + + + + org.eclipse.jetty.annotations.maxWait + 240 + + + + /midpoint + + + true + + -Xdebug -Xrunjdwp:transport=dt_socket,address=5000,server=y,suspend=n + + + + + pl.project13.maven + git-commit-id-plugin + 3.0.1 + + + + org.apache.maven.plugins + maven-shade-plugin + 2.3 + + + org.apache.maven.plugins + maven-enforcer-plugin + 3.0.0-M2 + + + enforce + + + + 3.6 + + + + + + commons-logging:commons-logging + org.springframework:spring-jcl + + + + + + + + enforce + + + + + + + org.apache.maven.plugins + maven-dependency-plugin + 3.1.1e1 + + + analyze + + analyze-only + + + true + true + + + + + + javax.xml.bind:jaxb-api + com.sun.activation:javax.activation + javax.activation:activation + + + xml-apis:xml-apis + + + jakarta.activation:jakarta.activation-api + jakarta.xml.bind:jakarta.xml.bind-api + org.glassfish.jaxb:xsom + org.glassfish.jaxb:jaxb-runtime + + + org.slf4j:jcl-over-slf4j + org.slf4j:slf4j-api + org.danekja:jdk-serializable-functional + + + + + + + maven-javadoc-plugin + 3.1.1 + + + org.apache.maven.plugins + maven-checkstyle-plugin + ${checkstyle.version} + + ${maven.multiModuleProjectDirectory}/config/checkstyle/checkstyle.xml + ${maven.multiModuleProjectDirectory}/config/checkstyle/checkstyle-suppressions.xml + UTF-8 + true + true + false + **/*.java + + **/*.properties,**/*.xml,**/*.xsd,**/*.wsdl,**/*.json,**/*.yaml,**/*.yml + + + + validate + validate + + check + + + + + + + + + + org.apache.maven.plugins + maven-compiler-plugin + 3.8.0 + + ${project.source.version} + ${project.source.version} + + + + org.apache.maven.plugins + maven-resources-plugin + 3.1.0 + + + com.rimerosolutions.maven.plugins + wrapper-maven-plugin + 0.0.4 + + + org.apache.maven.plugins + maven-plugin-plugin + + 3.6.0 + + + org.apache.maven.plugins + maven-deploy-plugin + 2.8.2 + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.apache.maven.plugins + maven-dependency-plugin + [3.1.1,) + + copy-dependencies + unpack + + + + + + + + + org.apache.cxf + cxf-codegen-plugin + [3.3.1,) + + wsdl2java + + + + + + + + + com.lukegb.mojo + gitdescribe-maven-plugin + [3.0,) + + gitdescribe + + + + + + + + + + + + org.apache.maven.plugins + maven-surefire-plugin + ${surefire.version} + + + default-test + test + + test + + + + + false + 1 + true + ${redirectTestOutputToFile} + false + + false + + src/test/resources/truststore.jks + target/midpoint-home + ${project.build.directory}/test-classes/logging.properties + + + ${surefire.args} + + + + /opt/jenkins_db_configs/ojdbc7.jar + + c:\midpoint\jdbc-drivers\ojdbc7.jar + + + testng-unit.xml + + + + suitename + Unit + + + listener + + com.evolveum.midpoint.tools.testng.TestListener,com.evolveum.midpoint.tools.testng.RetryListener + + + + + + + org.apache.maven.surefire + surefire-testng + ${surefire.version} + + + + + org.apache.maven.plugins + maven-failsafe-plugin + ${failsafe.version} + + + integration-test + integration-test + + integration-test + verify + + + + + ${redirectTestOutputToFile} + + src/test/resources/truststore.jks + target/midpoint-home + ${project.build.directory}/test-classes/logging.properties + + ${failsafe.args} + + testng-integration.xml + + + + suitename + Integration + + + listener + com.evolveum.midpoint.tools.testng.TestListener,com.evolveum.midpoint.tools.testng.RetryListener + + + + + /opt/jenkins_db_configs/ojdbc7.jar + + c:\midpoint\jdbc-drivers\ojdbc7.jar + + + + + + org.codehaus.mojo + findbugs-maven-plugin + 3.0.5 + + Max + Low + true + com.evolveum.midpoint.* + + + + maven-assembly-plugin + 3.1.1 + + + + + + + + + org.codehaus.mojo + findbugs-maven-plugin + + + org.apache.maven.plugins + maven-checkstyle-plugin + + ${checkstyle.version} + + ${maven.multiModuleProjectDirectory}/build-system/checkstyle-configs/checkstyle.xml + + UTF-8 + true + true + false + + + + + checkstyle + + + + + + + + + + dist + + + !skipDist + + + + dist + + + + + + extratest + + true + + + + + jdk-11 + + 11 + + + 11 + + + + + + xerces + xercesImpl + ${xerces.version} + + + xml-apis + xml-apis + + + + + xalan + serializer + ${xalan.version} + + + xml-apis + xml-apis + + + + + + + + + jdk-8 + + 1.8 + + + 1.8 + + + + diff --git a/testing/conntest/pom.xml b/testing/conntest/pom.xml index e4f976f748f..4fb985978d4 100644 --- a/testing/conntest/pom.xml +++ b/testing/conntest/pom.xml @@ -162,6 +162,11 @@ + + com.evolveum.polygon + connector-powershell + test + com.evolveum.polygon connector-databasetable diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapSynchronizationTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapSynchronizationTest.java index 86996c24951..d16461a1f95 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapSynchronizationTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/AbstractLdapSynchronizationTest.java @@ -1,516 +1,511 @@ -package com.evolveum.midpoint.testing.conntest; -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; - -import java.util.List; - -import org.apache.directory.api.ldap.model.entry.DefaultModification; -import org.apache.directory.api.ldap.model.entry.Modification; -import org.apache.directory.api.ldap.model.entry.ModificationOperation; -import org.apache.directory.api.ldap.model.exception.LdapException; -import org.apache.directory.api.ldap.model.message.ModifyDnRequest; -import org.apache.directory.api.ldap.model.message.ModifyDnRequestImpl; -import org.apache.directory.api.ldap.model.message.ModifyDnResponse; -import org.apache.directory.api.ldap.model.name.Dn; -import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.Test; - -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.util.PrismAsserts; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.LiveSyncCapabilityType; - -/** - * @author Radovan Semancik - */ -@ContextConfiguration(locations = { "classpath:ctx-conntest-test-main.xml" }) -@DirtiesContext(classMode = ClassMode.AFTER_CLASS) -public abstract class AbstractLdapSynchronizationTest extends AbstractLdapTest { - - protected static final String ACCOUNT_HT_UID = "ht"; - protected static final String ACCOUNT_HT_CN = "Herman Toothrot"; - protected static final String ACCOUNT_HT_GIVENNAME = "Herman"; - protected static final String ACCOUNT_HT_SN = "Toothrot"; - protected static final String ACCOUNT_HT_SN_MODIFIED = "Torquemeda Marley"; - - protected static final String ACCOUNT_HTM_UID = "htm"; - protected static final String ACCOUNT_HTM_CN = "Horatio Torquemada Marley"; - - protected static final String GROUP_MONKEYS_CN = "monkeys"; - protected static final String GROUP_MONKEYS_DESCRIPTION = "Monkeys of Monkey Island"; - - protected static final String GROUP_FOOLS_CN = "fools"; - protected static final String GROUP_FOOLS_DESCRIPTION = "not quite the shilling"; - - protected abstract void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException; - - protected boolean syncCanDetectDelete() { - return true; - } - - @Override - public void initSystem(Task initTask, OperationResult initResult) throws Exception { - super.initSystem(initTask, initResult); - } - - @Test - public void test000Sanity() throws Exception { - cleanupDelete(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN)); - cleanupDelete(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); - cleanupDelete(toGroupDn(GROUP_MONKEYS_CN)); - cleanupDelete(toGroupDn(GROUP_FOOLS_CN)); - } - - @Override - protected void assertAdditionalCapabilities(List nativeCapabilities) { - super.assertAdditionalCapabilities(nativeCapabilities); - - assertCapability(nativeCapabilities, LiveSyncCapabilityType.class); - } - - @Test - public void test800ImportSyncTask() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - addObject(getSyncTaskFile(), task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - long tsEnd = System.currentTimeMillis(); - - assertStepSyncToken(getSyncTaskOid(), 0, tsStart, tsEnd); - } - - @Test - public void test801SyncAddAccountHt() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - addLdapAccount(ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - displayUsers(); - - PrismObject user = findUserByUsername(ACCOUNT_HT_UID); - assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); - assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); - - assertStepSyncToken(getSyncTaskOid(), 1, tsStart, tsEnd); - } - - /** - * Changing account sn directly. - * Do not change cn here. But even if sn is not changed, this triggers rename in the AD case. - */ - @Test - public void test802ModifyAccountHtSn() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - LdapNetworkConnection connection = ldapConnect(); - Modification modSn = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "sn", ACCOUNT_HT_SN_MODIFIED); - connection.modify(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN), modSn); - ldapDisconnect(connection); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - PrismObject user = findUserByUsername(ACCOUNT_HT_UID); - assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); - assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); - - assertStepSyncToken(getSyncTaskOid(), 2, tsStart, tsEnd); - - } - - @Test - public void test810SyncAddGroupMonkeys() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - if (needsGroupFakeMemeberEntry()) { - addLdapGroup(GROUP_MONKEYS_CN, GROUP_MONKEYS_DESCRIPTION, "uid=fake," + getPeopleLdapSuffix()); - } else { - addLdapGroup(GROUP_MONKEYS_CN, GROUP_MONKEYS_DESCRIPTION); - } - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - PrismObject role = findObjectByName(RoleType.class, GROUP_MONKEYS_CN); - display("Role", role); - assertNotNull("no role " + GROUP_MONKEYS_CN, role); - PrismAsserts.assertPropertyValue(role, RoleType.F_DESCRIPTION, GROUP_MONKEYS_DESCRIPTION); - assertNotNull("No role " + GROUP_MONKEYS_CN + " created", role); - - assertStepSyncToken(getSyncTaskOid(), 3, tsStart, tsEnd); - } - - @Test - public void test817RenameAccount() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - LdapNetworkConnection connection = ldapConnect(); - - ModifyDnRequest modDnRequest = new ModifyDnRequestImpl(); - modDnRequest.setName(new Dn(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN))); - modDnRequest.setNewRdn(toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); - modDnRequest.setDeleteOldRdn(true); - ModifyDnResponse modDnResponse = connection.modifyDn(modDnRequest); - display("Modified " + toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN) + " -> " + toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN) + ": " + modDnResponse); - - doAdditionalRenameModifications(connection); - - ldapDisconnect(connection); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); - assertNotNull("No user " + ACCOUNT_HTM_UID + " created", user); - assertUser(user, user.getOid(), ACCOUNT_HTM_UID, getAccountHtmCnAfterRename(), ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); - assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); - - assertStepSyncToken(getSyncTaskOid(), 4, tsStart, tsEnd); - - } - - protected String getAccountHtmCnAfterRename() { - return ACCOUNT_HT_CN; - } - - protected void doAdditionalRenameModifications(LdapNetworkConnection connection) throws LdapException { - // Nothing to do here - } - - @Test - public void test818DeleteAccountHtm() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - deleteLdapEntry(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - if (syncCanDetectDelete()) { - assertNull("User " + ACCOUNT_HTM_UID + " still exist", findUserByUsername(ACCOUNT_HTM_UID)); - assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); - } else { - // Just delete the user so we have consistent state for subsequent tests - deleteObject(UserType.class, user.getOid(), task, result); - } - - assertStepSyncToken(getSyncTaskOid(), 5, tsStart, tsEnd); - } - - // TODO: sync with "ALL" object class - - @Test - public void test819DeleteSyncTask() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - deleteObject(TaskType.class, getSyncTaskOid(), task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - assertNoObject(TaskType.class, getSyncTaskOid(), task, result); - } - - @Test - public void test820ImportSyncTaskInetOrgPerson() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - addObject(getSyncTaskInetOrgPersonFile(), task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - long tsEnd = System.currentTimeMillis(); - - PrismObject syncTask = getTask(getSyncTaskOid()); - display("Sync task after start", syncTask); - - assertStepSyncToken(getSyncTaskOid(), 5, tsStart, tsEnd); - } - - @Test - public void test821SyncAddAccountHt() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - addLdapAccount(ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - displayUsers(); - - PrismObject user = findUserByUsername(ACCOUNT_HT_UID); - assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); - assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); - - assertStepSyncToken(getSyncTaskOid(), 6, tsStart, tsEnd); - } - - @Test - public void test822ModifyAccountHt() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - LdapNetworkConnection connection = ldapConnect(); - Modification modCn = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "sn", ACCOUNT_HT_SN_MODIFIED); - connection.modify(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN), modCn); - ldapDisconnect(connection); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - PrismObject user = findUserByUsername(ACCOUNT_HT_UID); - assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); - assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); - - assertStepSyncToken(getSyncTaskOid(), 7, tsStart, tsEnd); - } - - /** - * Add a new group. Check that this event is ignored. - */ - @Test - public void test830AddGroupFools() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - addLdapGroup(GROUP_FOOLS_CN, GROUP_FOOLS_DESCRIPTION, toGroupDn("nobody")); - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - PrismObject roleFools = findObjectByName(RoleType.class, GROUP_FOOLS_CN); - assertNull("Unexpected role " + roleFools, roleFools); - - assertStepSyncToken(getSyncTaskOid(), 8, tsStart, tsEnd); - } - - @Test - public void test837RenameAccount() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - LdapNetworkConnection connection = ldapConnect(); - - ModifyDnRequest modDnRequest = new ModifyDnRequestImpl(); - modDnRequest.setName(new Dn(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN))); - modDnRequest.setNewRdn(toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); - modDnRequest.setDeleteOldRdn(true); - ModifyDnResponse modDnResponse = connection.modifyDn(modDnRequest); - display("Modified " + toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN) + " -> " + toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN) + ": " + modDnResponse); - - doAdditionalRenameModifications(connection); - - ldapDisconnect(connection); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); - assertNotNull("No user " + ACCOUNT_HTM_UID + " created", user); - assertUser(user, user.getOid(), ACCOUNT_HTM_UID, getAccountHtmCnAfterRename(), ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); - assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); - - assertStepSyncToken(getSyncTaskOid(), 9, tsStart, tsEnd); - - } - - // TODO: create object of a different object class. See that it is ignored by sync. - - @Test - public void test838DeleteAccountHtm() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - deleteLdapEntry(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); - - waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - if (syncCanDetectDelete()) { - assertNull("User " + ACCOUNT_HTM_UID + " still exist", findUserByUsername(ACCOUNT_HTM_UID)); - assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); - } else { - // Just delete the user so we have consistent state for subsequent tests - deleteObject(UserType.class, user.getOid(), task, result); - } - - assertStepSyncToken(getSyncTaskOid(), 10, tsStart, tsEnd); - } - - @Test - public void test839DeleteSyncTask() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - deleteObject(TaskType.class, getSyncTaskOid(), task, result); - - // THEN - then(); - assertSuccess(result); - - assertNoObject(TaskType.class, getSyncTaskOid(), task, result); - } - -} +package com.evolveum.midpoint.testing.conntest; +/* + * Copyright (c) 2010-2020 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +import static org.testng.AssertJUnit.assertNotNull; +import static org.testng.AssertJUnit.assertNull; + +import java.util.List; + +import org.apache.directory.api.ldap.model.entry.DefaultModification; +import org.apache.directory.api.ldap.model.entry.Modification; +import org.apache.directory.api.ldap.model.entry.ModificationOperation; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.message.ModifyDnRequest; +import org.apache.directory.api.ldap.model.message.ModifyDnRequestImpl; +import org.apache.directory.api.ldap.model.message.ModifyDnResponse; +import org.apache.directory.api.ldap.model.name.Dn; +import org.apache.directory.ldap.client.api.LdapNetworkConnection; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.Test; + +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.util.PrismAsserts; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.util.exception.ObjectNotFoundException; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.resource.capabilities_3.LiveSyncCapabilityType; + +/** + * @author Radovan Semancik + */ +@ContextConfiguration(locations = { "classpath:ctx-conntest-test-main.xml" }) +@DirtiesContext(classMode = ClassMode.AFTER_CLASS) +public abstract class AbstractLdapSynchronizationTest extends AbstractLdapTest { + + protected static final String ACCOUNT_HT_UID = "ht"; + protected static final String ACCOUNT_HT_CN = "Herman Toothrot"; + protected static final String ACCOUNT_HT_GIVENNAME = "Herman"; + protected static final String ACCOUNT_HT_SN = "Toothrot"; + protected static final String ACCOUNT_HT_SN_MODIFIED = "Torquemeda Marley"; + + protected static final String ACCOUNT_HTM_UID = "htm"; + protected static final String ACCOUNT_HTM_CN = "Horatio Torquemada Marley"; + + protected static final String GROUP_MONKEYS_CN = "monkeys"; + protected static final String GROUP_MONKEYS_DESCRIPTION = "Monkeys of Monkey Island"; + + protected static final String GROUP_FOOLS_CN = "fools"; + protected static final String GROUP_FOOLS_DESCRIPTION = "not quite the shilling"; + + protected abstract void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException; + + protected boolean syncCanDetectDelete() { + return true; + } + + @Override + public void initSystem(Task initTask, OperationResult initResult) throws Exception { + super.initSystem(initTask, initResult); + } + + @Test + public void test000Sanity() throws Exception { + cleanupDelete(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN)); + cleanupDelete(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); + cleanupDelete(toGroupDn(GROUP_MONKEYS_CN)); + cleanupDelete(toGroupDn(GROUP_FOOLS_CN)); + } + + @Override + protected void assertAdditionalCapabilities(List nativeCapabilities) { + super.assertAdditionalCapabilities(nativeCapabilities); + + assertCapability(nativeCapabilities, LiveSyncCapabilityType.class); + } + + @Test + public void test800ImportSyncTask() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + addObject(getSyncTaskFile(), task, result); + + // THEN + then(); + assertSuccess(result); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + long tsEnd = System.currentTimeMillis(); + + assertStepSyncToken(getSyncTaskOid(), 0, tsStart, tsEnd); + } + + @Test + public void test801SyncAddAccountHt() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + addLdapAccount(ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + displayUsers(); + + PrismObject user = findUserByUsername(ACCOUNT_HT_UID); + assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); + assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); + + assertStepSyncToken(getSyncTaskOid(), 1, tsStart, tsEnd); + } + + /** + * Changing account sn directly. + * Do not change cn here. But even if sn is not changed, this triggers rename in the AD case. + */ + @Test + public void test802ModifyAccountHtSn() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + LdapNetworkConnection connection = ldapConnect(); + Modification modSn = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "sn", ACCOUNT_HT_SN_MODIFIED); + connection.modify(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN), modSn); + ldapDisconnect(connection); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + PrismObject user = findUserByUsername(ACCOUNT_HT_UID); + assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); + assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); + + assertStepSyncToken(getSyncTaskOid(), 2, tsStart, tsEnd); + + } + + @Test + public void test810SyncAddGroupMonkeys() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + if (needsGroupFakeMemeberEntry()) { + addLdapGroup(GROUP_MONKEYS_CN, GROUP_MONKEYS_DESCRIPTION, "uid=fake," + getPeopleLdapSuffix()); + } else { + addLdapGroup(GROUP_MONKEYS_CN, GROUP_MONKEYS_DESCRIPTION); + } + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + PrismObject role = findObjectByName(RoleType.class, GROUP_MONKEYS_CN); + display("Role", role); + assertNotNull("no role " + GROUP_MONKEYS_CN, role); + PrismAsserts.assertPropertyValue(role, RoleType.F_DESCRIPTION, GROUP_MONKEYS_DESCRIPTION); + assertNotNull("No role " + GROUP_MONKEYS_CN + " created", role); + + assertStepSyncToken(getSyncTaskOid(), 3, tsStart, tsEnd); + } + + @Test + public void test817RenameAccount() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + LdapNetworkConnection connection = ldapConnect(); + + ModifyDnRequest modDnRequest = new ModifyDnRequestImpl(); + modDnRequest.setName(new Dn(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN))); + modDnRequest.setNewRdn(toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); + modDnRequest.setDeleteOldRdn(true); + ModifyDnResponse modDnResponse = connection.modifyDn(modDnRequest); + display("Modified " + toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN) + " -> " + toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN) + ": " + modDnResponse); + + doAdditionalRenameModifications(connection); + + ldapDisconnect(connection); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); + assertNotNull("No user " + ACCOUNT_HTM_UID + " created", user); + assertUser(user, user.getOid(), ACCOUNT_HTM_UID, getAccountHtmCnAfterRename(), ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); + assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); + + assertStepSyncToken(getSyncTaskOid(), 4, tsStart, tsEnd); + + } + + protected String getAccountHtmCnAfterRename() { + return ACCOUNT_HT_CN; + } + + protected void doAdditionalRenameModifications(LdapNetworkConnection connection) throws LdapException { + // Nothing to do here + } + + @Test + public void test818DeleteAccountHtm() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + deleteLdapEntry(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + if (syncCanDetectDelete()) { + assertNull("User " + ACCOUNT_HTM_UID + " still exist", findUserByUsername(ACCOUNT_HTM_UID)); + assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); + } else { + // Just delete the user so we have consistent state for subsequent tests + deleteObject(UserType.class, user.getOid(), task, result); + } + + assertStepSyncToken(getSyncTaskOid(), 5, tsStart, tsEnd); + } + + // TODO: sync with "ALL" object class + + @Test + public void test819DeleteSyncTask() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + deleteObject(TaskType.class, getSyncTaskOid(), task, result); + + // THEN + then(); + assertSuccess(result); + + assertNoObject(TaskType.class, getSyncTaskOid(), task, result); + } + + @Test + public void test820ImportSyncTaskInetOrgPerson() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + addObject(getSyncTaskInetOrgPersonFile(), task, result); + + // THEN + then(); + assertSuccess(result); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + long tsEnd = System.currentTimeMillis(); + + PrismObject syncTask = getTask(getSyncTaskOid()); + display("Sync task after start", syncTask); + + assertStepSyncToken(getSyncTaskOid(), 5, tsStart, tsEnd); + } + + @Test + public void test821SyncAddAccountHt() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + addLdapAccount(ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + displayUsers(); + + PrismObject user = findUserByUsername(ACCOUNT_HT_UID); + assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); + assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); + + assertStepSyncToken(getSyncTaskOid(), 6, tsStart, tsEnd); + } + + @Test + public void test822ModifyAccountHt() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + LdapNetworkConnection connection = ldapConnect(); + Modification modCn = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, "sn", ACCOUNT_HT_SN_MODIFIED); + connection.modify(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN), modCn); + ldapDisconnect(connection); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + PrismObject user = findUserByUsername(ACCOUNT_HT_UID); + assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); + assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); + + assertStepSyncToken(getSyncTaskOid(), 7, tsStart, tsEnd); + } + + /** + * Add a new group. Check that this event is ignored. + */ + @Test + public void test830AddGroupFools() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + addLdapGroup(GROUP_FOOLS_CN, GROUP_FOOLS_DESCRIPTION, toGroupDn("nobody")); + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + PrismObject roleFools = findObjectByName(RoleType.class, GROUP_FOOLS_CN); + assertNull("Unexpected role " + roleFools, roleFools); + + assertStepSyncToken(getSyncTaskOid(), 8, tsStart, tsEnd); + } + + @Test + public void test837RenameAccount() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + LdapNetworkConnection connection = ldapConnect(); + + ModifyDnRequest modDnRequest = new ModifyDnRequestImpl(); + modDnRequest.setName(new Dn(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN))); + modDnRequest.setNewRdn(toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); + modDnRequest.setDeleteOldRdn(true); + ModifyDnResponse modDnResponse = connection.modifyDn(modDnRequest); + display("Modified " + toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN) + " -> " + toAccountRdn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN) + ": " + modDnResponse); + + doAdditionalRenameModifications(connection); + + ldapDisconnect(connection); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); + assertNotNull("No user " + ACCOUNT_HTM_UID + " created", user); + assertUser(user, user.getOid(), ACCOUNT_HTM_UID, getAccountHtmCnAfterRename(), ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN_MODIFIED); + assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); + + assertStepSyncToken(getSyncTaskOid(), 9, tsStart, tsEnd); + + } + + // TODO: create object of a different object class. See that it is ignored by sync. + + @Test + public void test838DeleteAccountHtm() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + PrismObject user = findUserByUsername(ACCOUNT_HTM_UID); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + deleteLdapEntry(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + if (syncCanDetectDelete()) { + assertNull("User " + ACCOUNT_HTM_UID + " still exist", findUserByUsername(ACCOUNT_HTM_UID)); + assertNull("User " + ACCOUNT_HT_UID + " still exist", findUserByUsername(ACCOUNT_HT_UID)); + } else { + // Just delete the user so we have consistent state for subsequent tests + deleteObject(UserType.class, user.getOid(), task, result); + } + + assertStepSyncToken(getSyncTaskOid(), 10, tsStart, tsEnd); + } + + @Test + public void test839DeleteSyncTask() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + deleteObject(TaskType.class, getSyncTaskOid(), task, result); + + // THEN + then(); + assertSuccess(result); + + assertNoObject(TaskType.class, getSyncTaskOid(), task, result); + } + +} diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java index 96fdf4fbcc2..0dd0e22f648 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java @@ -1,2308 +1,2385 @@ -/* - * Copyright (c) 2015-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.testing.conntest.ad; - -import static org.testng.AssertJUnit.*; - -import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_CREDENTIALS_PASSWORD_VALUE; - -import java.io.File; -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.util.Collection; -import java.util.List; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; - -import org.apache.directory.api.ldap.model.cursor.CursorException; -import org.apache.directory.api.ldap.model.entry.DefaultEntry; -import org.apache.directory.api.ldap.model.entry.Entry; -import org.apache.directory.api.ldap.model.exception.LdapException; -import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; -import org.apache.directory.api.ldap.model.name.Ava; -import org.apache.directory.api.ldap.model.name.Rdn; -import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.testng.AssertJUnit; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; -import com.evolveum.midpoint.model.api.ModelExecuteOptions; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.delta.PropertyDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectPaging; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.prism.query.OrderDirection; -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.schema.SearchResultList; -import com.evolveum.midpoint.schema.SearchResultMetadata; -import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.internals.InternalCounters; -import com.evolveum.midpoint.schema.processor.ResourceAttribute; -import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; -import com.evolveum.midpoint.schema.processor.ResourceSchema; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.schema.util.MiscSchemaUtil; -import com.evolveum.midpoint.schema.util.ObjectQueryUtil; -import com.evolveum.midpoint.schema.util.ShadowUtil; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.IntegrationTestTools; -import com.evolveum.midpoint.test.util.MidPointTestConstants; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.testing.conntest.AbstractLdapTest; -import com.evolveum.midpoint.testing.conntest.UserLdapConnectionConfig; -import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SystemException; -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; - -/** - * @author semancik - */ -@Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) -public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest - implements AdTestMixin { - - protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ad-ldap-multidomain"); - - protected static final File ROLE_PIRATES_FILE = new File(TEST_DIR, "role-pirate.xml"); - protected static final String ROLE_PIRATES_OID = "5dd034e8-41d2-11e5-a123-001e8c717e5b"; - - protected static final File ROLE_SUBMISSIVE_FILE = new File(TEST_DIR, "role-submissive.xml"); - protected static final String ROLE_SUBMISSIVE_OID = "0c0c81b2-d0a1-11e5-b51e-0309a826745e"; - - protected static final File ROLE_META_ORG_FILE = new File(TEST_DIR, "role-meta-org.xml"); - protected static final String ROLE_META_ORG_OID = "f2ad0ace-45d7-11e5-af54-001e8c717e5b"; - - protected static final File ROLE_META_ORG_GROUP_FILE = new File(TEST_DIR, "role-meta-org-group.xml"); - protected static final String ROLE_META_ORG_GROUP_OID = "c5d3294a-0d8e-11e7-bd9d-ff848c2e7e3f"; - - protected static final String ACCOUNT_JACK_SAM_ACCOUNT_NAME = "jack"; - protected static final String ACCOUNT_JACK_SID = "S-1-5-21-3305462238-3617280118-659738602-4878"; - protected static final String ACCOUNT_JACK_FULL_NAME = "Jack Sparrow"; - protected static final String ACCOUNT_JACK_PASSWORD = "qwe.123"; - - protected static final String USER_CPTBARBOSSA_FULL_NAME = "Captain Hector Barbossa"; - - private static final String GROUP_PIRATES_NAME = "pirates"; - private static final String GROUP_MELEE_ISLAND_NAME = "Mêlée Island"; - private static final String GROUP_MELEE_ISLAND_ALT_NAME = "Alternative Mêlée Island"; - private static final String GROUP_MELEE_ISLAND_PIRATES_NAME = "Mêlée Island Pirates"; - private static final String GROUP_MELEE_ISLAND_PIRATES_DESCRIPTION = "swashbuckle and loot"; - - protected static final int NUMBER_OF_ACCOUNTS = 18; - private static final String ASSOCIATION_GROUP_NAME = "group"; - - private static final String NS_EXTENSION = "http://whatever.com/my"; - private static final QName EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME = new QName(NS_EXTENSION, "showInAdvancedViewOnly"); - - protected static final File USER_SUBMAN_FILE = new File(TEST_DIR, "user-subman.xml"); - private static final String USER_SUBMAN_OID = "910ac45a-8bd6-11e6-9122-ef88d95095f0"; - private static final String USER_SUBMAN_USERNAME = "subman"; - private static final String USER_SUBMAN_GIVEN_NAME = "Sub"; - private static final String USER_SUBMAN_FAMILY_NAME = "Man"; - private static final String USER_SUBMAN_FULL_NAME = "Sub Man"; - private static final String USER_SUBMAN_PASSWORD = "sub.123"; - - private static final String USER_SUBDOG_USERNAME = "subdog"; - private static final String USER_SUBDOG_GIVEN_NAME = "Sub"; - private static final String USER_SUBDOG_FAMILY_NAME = "Dog"; - private static final String USER_SUBDOG_FULL_NAME = "Sub Dog"; - - protected static final File USER_SUBMARINE_FILE = new File(TEST_DIR, "user-submarine.xml"); - private static final String USER_SUBMARINE_OID = "c4377f86-8be9-11e6-8ef5-c3c56ff64b09"; - private static final String USER_SUBMARINE_USERNAME = "submarine"; - private static final String USER_SUBMARINE_GIVEN_NAME = "Sub"; - private static final String USER_SUBMARINE_FAMILY_NAME = "Marine"; - private static final String USER_SUBMARINE_FULL_NAME = "Sub Marine"; - - private static final String INTENT_GROUP = "group"; - private static final String INTENT_OU_TOP = "ou-top"; - - private static final String USER_EMPTYHEAD_NAME = "emptyhead"; - - private static final String PROXY_ADDRES_ADDR_UPCASE = "smpt:ADDR"; - private static final String PROXY_ADDRES_ADDR_LOWCASE = "smpt:addr"; - - private static final String OBJECT_CATEGORY_PERSON = "CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com"; - private static final String OBJECT_CATEGORY_GROUP = "CN=Group,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com"; - - private static final String USER_GUYBRUSH_PASSWORD_123 = "wanna.be.a.123"; - private static final String USER_GUYBRUSH_PASSWORD_333 = "wanna.be.a.333"; - - private boolean allowDuplicateSearchResults = false; - - protected String jackAccountOid; - protected String groupPiratesOid; - protected long jackLockoutTimestamp; - protected String accountBarbossaOid; - protected String orgMeleeIslandOid; - protected String groupMeleeIslandOid; - protected String ouMeleeIslandOid; - protected String roleMeleeIslandPiratesOid; - protected String groupMeleeIslandPiratesOid; - - private String accountSubmanOid; - - private String accountSubmarineOid; - - @Override - public String getStartSystemCommand() { - return null; - } - - @Override - public String getStopSystemCommand() { - return null; - } - - @Override - protected File getBaseDir() { - return TEST_DIR; - } - - @Override - protected String getSyncTaskOid() { - return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b"; - } - - @Override - protected boolean useSsl() { - return true; - } - - @Override - protected String getLdapSuffix() { - return "DC=ad,DC=evolveum,DC=com"; - } - - @Override - protected String getLdapBindDn() { - return "CN=midpoint,CN=Users,DC=ad,DC=evolveum,DC=com"; - } - - @Override - protected String getLdapBindPassword() { - return "qwe.123"; - } - - @Override - protected int getSearchSizeLimit() { - return -1; - } - - @Override - public String getPrimaryIdentifierAttributeName() { - return "objectGUID"; - } - - @Override - protected String getPeopleLdapSuffix() { - return "CN=Users," + getLdapSuffix(); - } - - @Override - protected String getGroupsLdapSuffix() { - return "CN=Users," + getLdapSuffix(); - } - - protected String getLdapSubSuffix() { - return "DC=sub,DC=ad,DC=evolveum,DC=com"; - } - - protected String getPeopleLdapSubSuffix() { - return "CN=Users," + getLdapSubSuffix(); - } - - @Override - protected String getLdapAccountObjectClass() { - return "user"; - } - - @Override - protected String getLdapGroupObjectClass() { - return "group"; - } - - @Override - protected String getLdapGroupMemberAttribute() { - return "member"; - } - - private QName getAssociationGroupQName() { - return new QName(MidPointConstants.NS_RI, ASSOCIATION_GROUP_NAME); - } - - @Override - protected boolean allowDuplicateSearchResults() { - return allowDuplicateSearchResults; - } - - @Override - protected boolean isGroupMemberMandatory() { - return false; - } - - protected String getOrgsLdapSuffix() { - return "OU=Org," + getLdapSuffix(); - } - - private UserLdapConnectionConfig getSubLdapConnectionConfig() { - UserLdapConnectionConfig config = new UserLdapConnectionConfig(); - config.setLdapHost("hydra.ad.evolveum.com"); - config.setLdapPort(getLdapServerPort()); - config.setBindDn("CN=midpoint,CN=Users,DC=sub,DC=ad,DC=evolveum,DC=com"); - config.setBindPassword(getLdapBindPassword()); - config.setBaseContext(getLdapSubSuffix()); - return config; - } - - protected abstract File getReconciliationTaskFile(); - - protected abstract String getReconciliationTaskOid(); - - protected String getLdapConnectorClassName() { - return AD_CONNECTOR_TYPE; - } - - @Override - public void initSystem(Task initTask, OperationResult initResult) throws Exception { - super.initSystem(initTask, initResult); - - binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_OBJECT_GUID_NAME); - binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_UNICODE_PWD_NAME); - - // Users - repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); - repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); - repoAddObjectFromFile(USER_SUBMAN_FILE, initResult); - repoAddObjectFromFile(USER_SUBMARINE_FILE, initResult); - - // Roles - repoAddObjectFromFile(ROLE_END_USER_FILE, initResult); - repoAddObjectFromFile(ROLE_PIRATES_FILE, initResult); - repoAddObjectFromFile(ROLE_SUBMISSIVE_FILE, initResult); - repoAddObjectFromFile(ROLE_META_ORG_FILE, initResult); - repoAddObjectFromFile(ROLE_META_ORG_GROUP_FILE, initResult); - - assignRole(USER_BARBOSSA_OID, ROLE_END_USER_OID); - - } - - @Test - public void test000Sanity() throws Exception { - assertLdapPassword(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME, ACCOUNT_JACK_PASSWORD); - cleanupDelete(toAccountDn(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME)); - cleanupDelete(toAccountDn(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME)); - cleanupDelete(toAccountDn(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME)); - cleanupDelete(getSubLdapConnectionConfig(), toAccountSubDn(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME)); - cleanupDelete(getSubLdapConnectionConfig(), toAccountSubDn(USER_SUBDOG_USERNAME, USER_SUBDOG_FULL_NAME)); - cleanupDelete(getSubLdapConnectionConfig(), toAccountSubDn(USER_SUBMARINE_USERNAME, USER_SUBMARINE_FULL_NAME)); - cleanupDelete(toGroupDn(GROUP_MELEE_ISLAND_NAME)); - cleanupDelete(toGroupDn(GROUP_MELEE_ISLAND_ALT_NAME)); - cleanupDelete(toOrgGroupDn(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME)); - cleanupDelete(toOrgGroupDn(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME)); - cleanupDelete(toOrgDn(GROUP_MELEE_ISLAND_NAME)); - cleanupDelete("ou=underMelee," + toOrgDn(GROUP_MELEE_ISLAND_ALT_NAME)); - cleanupDelete(toOrgDn(GROUP_MELEE_ISLAND_ALT_NAME)); - } - - @Test - @Override - public void test020Schema() throws Exception { - // IntegrationTestTools.displayXml("Resource XML", resource); - accountObjectClassDefinition = assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); - assertAdRefinedSchema(resource, getAccountObjectClass()); - assertExchangeSchema(resource, getAccountObjectClass(), prismContext); - - ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); - assertEquals("Unexpected number of schema definitions (limited by generation constraints)", 5, resourceSchema.getDefinitions().size()); - - assertLdapConnectorInstances(1); - } - - @Test - public void test100SeachJackBySamAccountName() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = createSamAccountNameQuery(ACCOUNT_JACK_SAM_ACCOUNT_NAME); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - when(); - SearchResultList> shadows = - modelService.searchObjects(ShadowType.class, query, null, task, result); - - // THEN - then(); - assertSuccess(result); - - assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); - - PrismObject shadow = shadows.get(0); - display("Shadow", shadow); - assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); - assertSid(shadow, ACCOUNT_JACK_SID); - assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); - jackAccountOid = shadow.getOid(); - -// assertConnectorOperationIncrement(2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = shadows.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(1); - } - - /** - * MID-3730 - */ - @Test - public void test101SeachJackByDn() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - String jackDn = toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME); - ObjectQuery query = createAccountShadowQueryByAttribute("dn", jackDn, resource); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - when(); - SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - - // THEN - then(); - assertSuccess(result); - - assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); - - PrismObject shadow = shadows.get(0); - display("Shadow", shadow); - assertAccountShadow(shadow, jackDn); - assertSid(shadow, ACCOUNT_JACK_SID); - assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); - -// assertConnectorOperationIncrement(2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = shadows.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(1); - } - - /** - * Search for non-existent DN should return no results. It should NOT - * throw an error. - *

- * MID-3730 - */ - @Test - public void test102SeachNotExistByDn() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - String dn = toAccountDn("idonoexist", "I am a Fiction"); - ObjectQuery query = createAccountShadowQueryByAttribute("dn", dn, resource); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - when(); - SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - - // THEN - then(); - assertSuccess(result); - - assertEquals("Unexpected search result: " + shadows, 0, shadows.size()); - -// assertConnectorOperationIncrement(2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - assertLdapConnectorInstances(1); - } - - @Test - public void test105SeachPiratesByCn() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); - ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_PIRATES_NAME), prismContext); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - when(); - SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - - // THEN - then(); - assertSuccess(result); - - assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); - - PrismObject shadow = shadows.get(0); - display("Shadow", shadow); - groupPiratesOid = shadow.getOid(); - assertObjectCategory(shadow, OBJECT_CATEGORY_GROUP); - -// assertConnectorOperationIncrement(1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = shadows.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(1); - } - - @Test - public void test110GetJack() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - long startOfTestMsTimestamp = getWin32Filetime(System.currentTimeMillis()); - - // WHEN - when(); - PrismObject shadow = modelService.getObject(ShadowType.class, jackAccountOid, null, task, result); - - // THEN - then(); - assertSuccess(result); - - display("Shadow", shadow); - assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); - jackAccountOid = shadow.getOid(); - - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - - assertAttribute(shadow, "dn", "CN=Jack Sparrow,CN=Users,DC=ad,DC=evolveum,DC=com"); - assertAttribute(shadow, "cn", ACCOUNT_JACK_FULL_NAME); - assertAttribute(shadow, "sn", "Sparrow"); - assertAttribute(shadow, "description", "The best pirate the world has ever seen"); - assertAttribute(shadow, "sAMAccountName", ACCOUNT_JACK_SAM_ACCOUNT_NAME); - assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); - List lastLogonValues = ShadowUtil.getAttributeValues(shadow, new QName(getResourceNamespace(), "lastLogon")); - assertEquals("Wrong number of lastLong values: " + lastLogonValues, 1, lastLogonValues.size()); - if (lastLogonValues.get(0) > startOfTestMsTimestamp) { - fail("Wrong lastLogon, expected it to be less than " + startOfTestMsTimestamp + ", but was " + lastLogonValues.get(0)); - } - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - assertLdapConnectorInstances(1); - } - - /** - * No paging. It should return all accounts. - */ - @Test - public void test150SeachAllAccounts() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - SearchResultList> searchResultList = doSearch(query, - NUMBER_OF_ACCOUNTS, task, result); - - // TODO: Why 14? Why not 1? - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 14); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * This is in one block. - */ - @Test - public void test152SeachFirst2Accounts() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(); - paging.setMaxSize(2); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 2, task, result); - - // TODO: Why 2? Why not 1? - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - @Test - public void test154SeachFirst11Accounts() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(); - paging.setMaxSize(11); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 11, task, result); - - // TODO: Why 2? Why not 1? - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - @Test - public void test162SeachFirst2AccountsOffset0() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(); - paging.setOffset(0); - paging.setMaxSize(2); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 2, task, result); - - // TODO: Why 2? Why not 1? - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * There is offset, so VLV should be used. - * No explicit sorting. - */ - @Test - public void test172Search2AccountsOffset1() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 2, task, result); - - // TODO: Why 2? Why not 1? - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * There is offset, so VLV should be used. - * No explicit sorting. - */ - @Test - public void test174SeachFirst11AccountsOffset2() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(2, 11); - query.setPaging(paging); - - allowDuplicateSearchResults = true; - - // WHEN - SearchResultList> searchResultList = doSearch(query, 11, task, result); - - // THEN - allowDuplicateSearchResults = false; - - // TODO: Why 2? Why not 1? - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * There is offset, so VLV should be used. - * Explicit sorting. - */ - @Test - public void test182Search2AccountsOffset1SortCn() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); - paging.setOrdering(getAttributePath(resource, "cn"), OrderDirection.ASCENDING); - query.setPaging(paging); - - SearchResultList> shadows = doSearch(query, 2, task, result); - - assertAccountShadow(shadows.get(0), "CN=Adolf Supperior,CN=Users,DC=ad,DC=evolveum,DC=com"); -// assertAccountShadow(shadows.get(1), "CN=DiscoverySearchMailbox {D919BA05-46A6-415f-80AD-7E09334BB852},CN=Users,DC=ad,DC=evolveum,DC=com"); - - // TODO: Why 2? Why not 1? - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = shadows.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - @Test - public void test200AssignAccountBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - assignAccountToUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "title", null); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getShadowModel(shadowOid); - display("Shadow (model)", shadow); - accountBarbossaOid = shadow.getOid(); - Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); - String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); - assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); - - assertEquals("Wrong ICFS UID", - formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), - accountBarbossaIcfUid); - - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); - - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); - - // MID-4624 - ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); - assertNotNull("No createTimestamp in " + shadow, createTimestampAttribute); - XMLGregorianCalendar createTimestamp = createTimestampAttribute.getRealValue(); - long createTimestampMillis = XmlTypeConverter.toMillis(createTimestamp); - // LDAP server may be on a different host. Allow for some clock offset. - TestUtil.assertBetween("Wrong createTimestamp in " + shadow, roundTsDown(tsStart) - 120000, roundTsUp(tsEnd) + 120000, createTimestampMillis); - - assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test210ModifyAccountBarbossaTitle() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta delta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, ATTRIBUTE_TITLE_NAME); - ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); - PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( - ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); - delta.addModification(attrDelta); - - // WHEN - when(); - executeChanges(delta, null, task, result); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_TITLE_NAME, "Captain"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta delta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); - ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); - PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( - ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); - delta.addModification(attrDelta); - - // WHEN - when(); - executeChanges(delta, null, task, result); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "showInAdvancedViewOnly", "TRUE"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapConnectorInstances(2); - } - - /** - * Modify USER, test boolean value mapping. - */ - @Test - public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta delta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); - ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); - PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( - ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); - delta.addModification(attrDelta); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, ItemPath.create(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), - task, result, Boolean.FALSE); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "showInAdvancedViewOnly", "FALSE"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapConnectorInstances(2); - } - - /** - * Just normal modification of proxyAddress, directly on the account. - * As proxyAddress is multivalue, this is ADD and not REPLACE. This is what GUI would do. - * No previous value for proxyAddress is set in the AD account. - * MID-5330 - */ - @Test - public void test214ModifyAccountBarbossaProxyAddressesSimple() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta delta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, ATTRIBUTE_PROXY_ADDRESSES_NAME); - ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); - assertNotNull("No definition for attribute " + attrQName, attrDef); - PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationAddProperty( - ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, PROXY_ADDRES_ADDR_UPCASE); - delta.addModification(attrDelta); - - // WHEN - when(); - executeChanges(delta, null, task, result); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_PROXY_ADDRESSES_NAME, PROXY_ADDRES_ADDR_UPCASE); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test220ModifyUserBarbossaPasswordSelfServicePassword1() throws Exception { - testModifyUserBarbossaPasswordSelfServiceSuccess( - USER_BARBOSSA_PASSWORD, USER_BARBOSSA_PASSWORD_AD_1); - } - - /** - * Try to set the same password again. If this is "admin mode" (no runAs capability) - * the such change should be successful. In "selfservice mode" (runAs capability - in subclass) - * this change should fail. - */ - @Test - public void test222ModifyUserBarbossaPasswordSelfServicePassword1Again() throws Exception { - testModifyUserBarbossaPasswordSelfServiceSuccess( - USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_1); - } - - /** - * Change to different password. This should go well for both admin and self-service. - * MID-5242 - */ - @Test - public void test224ModifyUserBarbossaPasswordSelfServicePassword2() throws Exception { - testModifyUserBarbossaPasswordSelfServiceSuccess( - USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_2); - } - - /** - * Change password back to the first password. This password was used before. - * In admin mode this should go well. Admin can set password to anything. - * But in self-service mode (in subclass) this should fail due to password history check. - */ - @Test - public void test226ModifyUserBarbossaPasswordSelfServicePassword1AgainAgain() throws Exception { - testModifyUserBarbossaPasswordSelfServiceSuccess( - USER_BARBOSSA_PASSWORD_AD_2, USER_BARBOSSA_PASSWORD_AD_1); - } - - protected void testModifyUserBarbossaPasswordSelfServiceSuccess(String oldPassword, String newPassword) throws Exception { - // GIVEN - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, oldPassword); - - login(USER_BARBOSSA_USERNAME); - - Task task = getTestTask(); - task.setChannel(SchemaConstants.CHANNEL_GUI_SELF_SERVICE_URI); - OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createOldNewPasswordDelta(USER_BARBOSSA_OID, - oldPassword, newPassword); - - // WHEN - when(); - executeChanges(objectDelta, null, task, result); - - // THEN - then(); - login(USER_ADMINISTRATOR_USERNAME); - assertSuccess(result); - - assertBarbossaEnabled(newPassword); - - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, newPassword); - - assertLdapConnectorInstances(2); - } - - protected void testModifyUserBarbossaPasswordSelfServiceFailure( - String oldPassword, String newPassword) throws Exception { - // GIVEN - login(USER_BARBOSSA_USERNAME); - - Task task = getTestTask(); - task.setChannel(SchemaConstants.CHANNEL_GUI_SELF_SERVICE_URI); - OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createOldNewPasswordDelta(USER_BARBOSSA_OID, - oldPassword, newPassword); - - // WHEN - when(); - executeChanges(objectDelta, null, task, result); - - // THEN - then(); - login(USER_ADMINISTRATOR_USERNAME); - assertPartialError(result); - - assertBarbossaEnabled(newPassword); - assertUserAfter(USER_BARBOSSA_OID) - .assertPassword(newPassword); - - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, oldPassword); - - assertLdapConnectorInstances(2); - } - - @Test - public void test230DisableUserBarbossa() throws Exception { - // precondition - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - task, result, ActivationStatusType.DISABLED); - - // THEN - then(); - assertSuccess(result); - - assertBarbossaDisabled(USER_BARBOSSA_PASSWORD_AD_1); - } - - /** - * MID-4041 - */ - @Test - public void test232ReconcileBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - reconcileUser(USER_BARBOSSA_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - assertBarbossaDisabled(USER_BARBOSSA_PASSWORD_AD_1); - } - - /** - * MID-4041 - */ - @Test - public void test236EnableUserBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - task, result, ActivationStatusType.ENABLED); - - // THEN - then(); - assertSuccess(result); - - assertBarbossaEnabled(USER_BARBOSSA_PASSWORD_AD_1); - - assertLdapConnectorInstances(2); - } - - /** - * MID-4041 - */ - @Test - public void test237ReconcileBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - reconcileUser(USER_BARBOSSA_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - assertBarbossaEnabled(USER_BARBOSSA_PASSWORD_AD_1); - - assertLdapConnectorInstances(2); - } - - /** - * MID-4041 - */ - @Test - public void test238DisableUserBarbossaRawAndReconcile() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - modifyUserReplace(USER_BARBOSSA_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - ModelExecuteOptions.createRaw(), task, result, ActivationStatusType.DISABLED); - - // WHEN - when(); - reconcileUser(USER_BARBOSSA_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - assertBarbossaDisabled(USER_BARBOSSA_PASSWORD_AD_1); - - assertLdapConnectorInstances(2); - } - - /** - * MID-4041 - */ - @Test - public void test239EnableUserBarbossaRawAndReconcile() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - modifyUserReplace(USER_BARBOSSA_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - ModelExecuteOptions.createRaw(), task, result, ActivationStatusType.ENABLED); - - // WHEN - when(); - reconcileUser(USER_BARBOSSA_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - assertBarbossaEnabled(USER_BARBOSSA_PASSWORD_AD_1); - - assertLdapConnectorInstances(2); - } - - protected PrismObject assertBarbossaEnabled(String ldapPassword) throws Exception { - PrismObject user = getUser(USER_BARBOSSA_OID); - assertAdministrativeStatus(user, ActivationStatusType.ENABLED); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "title", "Captain"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - assertAttribute(entry, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "FALSE"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountEnabled(shadow); - - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, ldapPassword); - - return user; - } - - private void assertBarbossaDisabled(String password) throws Exception { - assertLdapConnectorInstances(2); - - PrismObject user = getUser(USER_BARBOSSA_OID); - assertAdministrativeStatus(user, ActivationStatusType.DISABLED); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - display("disabled Barbossa entry", entry); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - - assertAttribute(entry, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "TRUE"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountDisabled(shadow); - - try { - assertLdapPassword(null, entry, password); - AssertJUnit.fail("Password authentication works, but it should fail"); - } catch (SecurityException e) { - // this is expected - } - - assertLdapConnectorInstances(2); - } - - /** - * This should create account with a group. And the account shoudl be disabled. - */ - @Test - public void test250AssignGuybrushPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - -// ProtectedStringType userPasswordPs = new ProtectedStringType(); -// userPasswordPs.setClearValue(USER_GUYBRUSH_PASSWORD_333); -// modifyUserReplace(USER_GUYBRUSH_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); - modifyUserReplace(USER_GUYBRUSH_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - task, result, ActivationStatusType.DISABLED); - - // WHEN - when(); - assignRole(USER_GUYBRUSH_OID, ROLE_PIRATES_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - display("Entry", entry); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - - assertLdapGroupMember(entry, GROUP_PIRATES_NAME); - - PrismObject user = getUser(USER_GUYBRUSH_OID); - assertAdministrativeStatus(user, ActivationStatusType.DISABLED); - String shadowOid = getSingleLinkOid(user); - - PrismObject shadow = getObject(ShadowType.class, shadowOid); - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - assertAccountDisabled(shadow); - -// try { -// assertLdapPassword(null, entry, USER_GUYBRUSH_PASSWORD_333); -// AssertJUnit.fail("Password authentication works, but it should fail"); -// } catch (SecurityException e) { -// // this is expected, account is disabled -// } - - assertLdapConnectorInstances(2); - } - - @Test - public void test255ModifyUserGuybrushPassword() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ProtectedStringType userPasswordPs = new ProtectedStringType(); - userPasswordPs.setClearValue(USER_GUYBRUSH_PASSWORD_123); - - // WHEN - when(); - modifyUserReplace(USER_GUYBRUSH_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - display("Guybrush entry after", entry); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - - try { - assertLdapPassword(null, entry, USER_GUYBRUSH_PASSWORD_123); - AssertJUnit.fail("Password authentication works, but it should fail"); - } catch (SecurityException e) { - // this is expected, account is disabled - } - -// assertLdapConnectorInstances(2); - } - - @Test - public void test260EnableGyubrush() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_GUYBRUSH_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - task, result, ActivationStatusType.ENABLED); - - // THEN - then(); - assertSuccess(result); - - PrismObject user = getUser(USER_GUYBRUSH_OID); - assertAdministrativeStatus(user, ActivationStatusType.ENABLED); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountEnabled(shadow); - - assertLdapPassword(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); - - assertLdapConnectorInstances(2); - } - - /** - * Try to create an account without password. This should end up with an error. - * A reasonable error. - * MID-4046 - */ - @Test - public void test270AssignAccountToEmptyhead() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - PrismObject userBefore = createUser(USER_EMPTYHEAD_NAME, USER_EMPTYHEAD_NAME, true); - display("User before", userBefore); - addObject(userBefore); - String userEmptyheadOid = userBefore.getOid(); - - // WHEN - when(); - assignAccountToUser(userEmptyheadOid, getResourceOid(), null, task, result); - - // THEN - then(); - assertPartialError(result); - - assertMessageContains(result.getMessage(), "does not meet the length, complexity, or history requirement"); - - assertLdapConnectorInstances(2); - } - - /** - * Just make random test connection between the tests. Make sure that the - * test does not break anything. If it does the next tests will simply fail. - */ - @Test - public void test295TestConnection() throws Exception { - // GIVEN - Task task = getTestTask(); - - // WHEN - when(); - OperationResult testResult = modelService.testResource(getResourceOid(), task); - - // THEN - then(); - display("Test connection result", testResult); - TestUtil.assertSuccess("Test connection result", testResult); - - // Test is disposing connector facade and the entire connector pool. - // Therefore we are back at 1 instance. - assertLdapConnectorInstances(1); - } - - @Test - public void test300AssignBarbossaPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - assignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - display("Entry", entry); - assertAttribute(entry, "title", "Captain"); - - assertLdapGroupMember(entry, GROUP_PIRATES_NAME); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - PrismObject shadow = getObject(ShadowType.class, shadowOid); - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - - assertLdapConnectorInstances(1); - } - - @Test - public void test390ModifyUserBarbossaRename() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_BARBOSSA_OID, UserType.F_NAME, - PrismTestUtil.createPolyString(USER_CPTBARBOSSA_USERNAME)); - objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, - PrismTestUtil.createPolyString(USER_CPTBARBOSSA_FULL_NAME)); - Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); - - // WHEN - when(); - modelService.executeChanges(deltas, null, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); - assertAttribute(entry, "title", "Captain"); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - display("Shadow after rename (model)", shadow); - - PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); - display("Shadow after rename (repo)", repoShadow); - - assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - -// assertLdapConnectorInstances(2); - } - - // TODO: create account with a group membership - - @Test - public void test395UnAssignBarbossaPirates() throws Exception { - // TODO: do this on another account. There is a bad interference with rename. - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - unassignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); - display("Entry", entry); - assertAttribute(entry, "title", "Captain"); - - assertLdapNoGroupMember(entry, GROUP_PIRATES_NAME); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - PrismObject shadow = getObject(ShadowType.class, shadowOid); - IntegrationTestTools.assertNoAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test399UnAssignAccountBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - unassignAccountFromUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertNoLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); - - PrismObject user = getUser(USER_BARBOSSA_OID); - assertNoLinkedAccount(user); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test500AddOrgMeleeIsland() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - PrismObject org = instantiateObject(OrgType.class); - OrgType orgType = org.asObjectable(); - orgType.setName(new PolyStringType(GROUP_MELEE_ISLAND_NAME)); - AssignmentType metaroleAssignment = new AssignmentType(); - ObjectReferenceType metaroleRef = new ObjectReferenceType(); - metaroleRef.setOid(ROLE_META_ORG_OID); - metaroleRef.setType(RoleType.COMPLEX_TYPE); - metaroleAssignment.setTargetRef(metaroleRef); - orgType.getAssignment().add(metaroleAssignment); - - // WHEN - when(); - addObject(org, task, result); - - // THEN - then(); - assertSuccess(result); - - orgMeleeIslandOid = org.getOid(); - assertLdapGroup(GROUP_MELEE_ISLAND_NAME); - assertLdapOrg(GROUP_MELEE_ISLAND_NAME); - - org = getObject(OrgType.class, orgMeleeIslandOid); - groupMeleeIslandOid = getLinkRefOid(org, getResourceOid(), ShadowKindType.ENTITLEMENT, INTENT_GROUP); - ouMeleeIslandOid = getLinkRefOid(org, getResourceOid(), ShadowKindType.GENERIC, INTENT_OU_TOP); - assertLinks(org, 2); - - PrismObject shadowGroup = getShadowModel(groupMeleeIslandOid); - display("Shadow: group (model)", shadowGroup); - - PrismObject shadowOu = getShadowModel(ouMeleeIslandOid); - display("Shadow: ou (model)", shadowOu); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test510AssignGuybrushMeleeIsland() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - assignOrg(USER_GUYBRUSH_OID, orgMeleeIslandOid, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - - PrismObject user = getUser(USER_GUYBRUSH_OID); - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getShadowModel(shadowOid); - display("Shadow (model)", shadow); - - assertLdapGroupMember(entry, GROUP_MELEE_ISLAND_NAME); - - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupMeleeIslandOid); - -// assertLdapConnectorInstances(2); - } - - /** - * Create role under the Melee Island org. This creates group in the orgstruct. - */ - @Test - public void test515AddOrgGroupMeleeIslandPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - PrismObject role = instantiateObject(RoleType.class); - RoleType roleType = role.asObjectable(); - roleType.setName(new PolyStringType(GROUP_MELEE_ISLAND_PIRATES_NAME)); - - AssignmentType metaroleAssignment = new AssignmentType(); - ObjectReferenceType metaroleRef = new ObjectReferenceType(); - metaroleRef.setOid(ROLE_META_ORG_GROUP_OID); - metaroleRef.setType(RoleType.COMPLEX_TYPE); - metaroleAssignment.setTargetRef(metaroleRef); - roleType.getAssignment().add(metaroleAssignment); - - AssignmentType orgAssignment = new AssignmentType(); - ObjectReferenceType orgRef = new ObjectReferenceType(); - orgRef.setOid(orgMeleeIslandOid); - orgRef.setType(OrgType.COMPLEX_TYPE); - orgAssignment.setTargetRef(orgRef); - roleType.getAssignment().add(orgAssignment); - - // WHEN - when(); - addObject(role, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - roleMeleeIslandPiratesOid = role.getOid(); - // TODO: assert LDAP object - - assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); - - PrismObject roleAfter = getObject(RoleType.class, roleMeleeIslandPiratesOid); - display("Role after", roleAfter); - groupMeleeIslandPiratesOid = getSingleLinkOid(roleAfter); - PrismObject shadow = getShadowModel(groupMeleeIslandPiratesOid); - display("Shadow (model)", shadow); - } - - /** - * Rename org unit. MidPoint should rename OU and ordinary group. - * AD will rename the group in the orgstruct automatically. We need to - * make sure that we can still access that group. - */ - @Test - public void test520RenameMeleeIsland() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - renameObject(OrgType.class, orgMeleeIslandOid, GROUP_MELEE_ISLAND_ALT_NAME, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - PrismObject orgAfter = getObject(OrgType.class, orgMeleeIslandOid); - groupMeleeIslandOid = getLinkRefOid(orgAfter, getResourceOid(), ShadowKindType.ENTITLEMENT, INTENT_GROUP); - ouMeleeIslandOid = getLinkRefOid(orgAfter, getResourceOid(), ShadowKindType.GENERIC, INTENT_OU_TOP); - assertLinks(orgAfter, 2); - - PrismObject shadowGroup = getShadowModel(groupMeleeIslandOid); - display("Shadow: group (model)", shadowGroup); - - PrismObject shadowOu = getShadowModel(ouMeleeIslandOid); - display("Shadow: ou (model)", shadowOu); - - assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); - assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); - - assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); - assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); - - assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); - assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); - - Entry entryGuybrush = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - - PrismObject user = getUser(USER_GUYBRUSH_OID); - String shadowAccountOid = getSingleLinkOid(user); - PrismObject shadowAccount = getShadowModel(shadowAccountOid); - display("Shadow: account (model)", shadowAccount); - - assertLdapGroupMember(entryGuybrush, GROUP_MELEE_ISLAND_ALT_NAME); - - IntegrationTestTools.assertAssociation(shadowAccount, getAssociationGroupQName(), groupMeleeIslandOid); - -// assertLdapConnectorInstances(2); - } - - /** - * AD renamed the pirate groups by itself. MidPoint does not know about it. - * The GUID that is stored in the shadow is still OK. But the DN is now out - * of date. Try to update the group. Make sure it works. - * It is expected that the GUI will be used as a primary identifier. - * Note: just reading the group will NOT work. MidPoint is too smart - * for that. It will transparently fix the situation. - */ - @Test - public void test522ModifyMeleeIslandPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyObjectReplaceProperty(ShadowType.class, groupMeleeIslandPiratesOid, - ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(MidPointConstants.NS_RI, "description")), - task, result, GROUP_MELEE_ISLAND_PIRATES_DESCRIPTION); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); - assertAttribute(entryOrgGroup, "description", GROUP_MELEE_ISLAND_PIRATES_DESCRIPTION); - - assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test524GetMeleeIslandPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - PrismObject shadow = modelService.getObject(ShadowType.class, groupMeleeIslandPiratesOid, null, task, result); - - // THEN - then(); - assertSuccess(result); - - display("Shadow after", shadow); - assertNotNull(shadow); - - assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); - assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); - assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); - assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); - Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); - display("Melee org", entryOrgGroup); - assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); - } - - @Test - public void test595DeleteOrgGroupMeleeIslandPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - deleteObject(RoleType.class, roleMeleeIslandPiratesOid, task, result); - - // THEN - then(); - assertSuccess(result); - - assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); - assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); - - assertNoObject(ShadowType.class, groupMeleeIslandPiratesOid); - -// assertLdapConnectorInstances(2); - } - - /** - * We create "underMelee" org that gets into the way of the delete. - * Melee cannot be deleted in an ordinary way. "tree delete" control must - * be used. This is configured in the connector config. - *

- * MID-5935 - */ - @Test - public void test599DeleteOrgMeleeIsland() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - createUnderMeleeEntry(); - - // WHEN - when(); - deleteObject(OrgType.class, orgMeleeIslandOid, task, result); - - // THEN - then(); - assertSuccess(result); - - assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); - assertNoLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); - assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); - assertNoLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); - - assertNoObject(ShadowType.class, groupMeleeIslandOid); - assertNoObject(ShadowType.class, ouMeleeIslandOid); - -// assertLdapConnectorInstances(2); - } - - protected void createUnderMeleeEntry() throws LdapException, IOException { - // This OU just gets into the way of the delete. - Entry entry = new DefaultEntry("ou=underMelee," + toOrgDn(GROUP_MELEE_ISLAND_ALT_NAME), - "objectclass", "organizationalUnit", - "ou", "underMelee"); - display("underMelee org", entry); - addLdapEntry(entry); - } - - @Test - public void test600AssignAccountSubman() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - assignRole(USER_SUBMAN_OID, ROLE_SUBMISSIVE_OID, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - display("Sub entry", entry); - assertAttribute(entry, "title", null); - - PrismObject userAfter = getUser(USER_SUBMAN_OID); - String shadowOid = getSingleLinkOid(userAfter); - PrismObject shadow = getShadowModel(shadowOid); - display("Shadow (model)", shadow); - accountSubmanOid = shadow.getOid(); - Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); - String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); - assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); - - assertEquals("Wrong ICFS UID", - formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), - accountBarbossaIcfUid); - - assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, USER_SUBMAN_PASSWORD); - - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - // MID-4624 - ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); - assertNotNull("No createTimestamp in " + shadow, createTimestampAttribute); - XMLGregorianCalendar createTimestamp = createTimestampAttribute.getRealValue(); - long createTimestampMillis = XmlTypeConverter.toMillis(createTimestamp); - // LDAP server may be on a different host. Allow for some clock offset. - TestUtil.assertBetween("Wrong createTimestamp in " + shadow, roundTsDown(tsStart) - 120000, roundTsUp(tsEnd) + 120000, createTimestampMillis); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test610ModifyUserSubmanTitle() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_SUBMAN_OID, UserType.F_TITLE, task, result, - createPolyString("Underdog")); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - display("Sub entry", entry); - assertAttribute(entry, "title", "Underdog"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - PrismObject user = getUser(USER_SUBMAN_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountSubmanOid, shadowOid); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test620ModifyUserSubmanPassword() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ProtectedStringType userPasswordPs = new ProtectedStringType(); - userPasswordPs.setClearValue("SuB.321"); - - // WHEN - when(); - modifyUserReplace(USER_SUBMAN_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - assertAttribute(entry, "title", "Underdog"); - assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, "SuB.321"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - PrismObject user = getUser(USER_SUBMAN_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountSubmanOid, shadowOid); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test630DisableUserSubman() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_SUBMAN_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - task, result, ActivationStatusType.DISABLED); - - // THEN - then(); - assertSuccess(result); - -// assertLdapConnectorInstances(2); - - PrismObject user = getUser(USER_SUBMAN_OID); - assertAdministrativeStatus(user, ActivationStatusType.DISABLED); - - Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountDisabled(shadow); - - try { - assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, "SuB.321"); - AssertJUnit.fail("Password authentication works, but it should fail"); - } catch (SecurityException e) { - // this is expected - } - -// assertLdapConnectorInstances(2); - } - - @Test - public void test639EnableUserSubman() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_SUBMAN_OID, - SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, - task, result, ActivationStatusType.ENABLED); - - // THEN - then(); - assertSuccess(result); - - PrismObject user = getUser(USER_SUBMAN_OID); - assertAdministrativeStatus(user, ActivationStatusType.ENABLED); - - Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountEnabled(shadow); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test690ModifyUserSubmanRename() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_SUBMAN_OID, UserType.F_NAME, - createPolyString(USER_SUBDOG_USERNAME)); - objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, - createPolyString(USER_SUBDOG_FULL_NAME)); - - // WHEN - when(); - executeChanges(objectDelta, null, task, result); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapSubAccount(USER_SUBDOG_USERNAME, USER_SUBDOG_FULL_NAME); - assertAttribute(entry, "title", "Underdog"); - - PrismObject user = getUser(USER_SUBMAN_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountSubmanOid, shadowOid); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - display("Shadow after rename (model)", shadow); - - PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); - display("Shadow after rename (repo)", repoShadow); - - assertNoLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - -// assertLdapConnectorInstances(2); - } - - @Test - public void test699UnAssignAccountSubdog() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - unassignRole(USER_SUBMAN_OID, ROLE_SUBMISSIVE_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - assertNoLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); - assertNoLdapSubAccount(USER_SUBDOG_USERNAME, USER_SUBDOG_FULL_NAME); - - PrismObject user = getUser(USER_SUBMAN_OID); - assertNoLinkedAccount(user); - -// assertLdapConnectorInstances(2); - } - - /** - * Create account and modify it in a very quick succession. - * This test is designed to check if we can live with a long - * global catalog update delay. - * MID-2926 - */ - @Test - public void test700AssignAccountSubmarineAndModify() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - assignRole(USER_SUBMARINE_OID, ROLE_SUBMISSIVE_OID, task, result); - - modifyUserReplace(USER_SUBMARINE_OID, UserType.F_TITLE, task, result, - PrismTestUtil.createPolyString("Underseadog")); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapSubAccount(USER_SUBMARINE_USERNAME, USER_SUBMARINE_FULL_NAME); - display("Sub entry", entry); - assertAttribute(entry, "title", "Underseadog"); - - PrismObject userAfter = getUser(USER_SUBMARINE_OID); - String shadowOid = getSingleLinkOid(userAfter); - PrismObject shadow = getShadowModel(shadowOid); - display("Shadow (model)", shadow); - accountSubmarineOid = shadow.getOid(); - Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); - String accountIcfUid = (String) identifiers.iterator().next().getRealValue(); - assertNotNull("No identifier in " + shadow, accountIcfUid); - - assertEquals("Wrong ICFS UID", - formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), - accountIcfUid); - - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - } - - @Test - public void test809UnAssignAccountSubmarine() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - unassignRole(USER_SUBMARINE_OID, ROLE_SUBMISSIVE_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - assertNoLdapSubAccount(USER_SUBMARINE_USERNAME, USER_SUBMARINE_FULL_NAME); - - PrismObject user = getUser(USER_SUBMARINE_OID); - assertNoLinkedAccount(user); - } - - @Test - public void test850ReconcileAccounts() throws Exception { - // GIVEN - assertUsers(6); - - // WHEN - when(); - addTask(getReconciliationTaskFile()); - - waitForTaskFinish(getReconciliationTaskOid(), true); - - // THEN - then(); - - assertUsers(15); - // TODO - -// assertLdapConnectorInstances(2); - } - - @Override - protected void assertAccountShadow(PrismObject shadow, String dn) throws SchemaException { - super.assertAccountShadow(shadow, dn); - ResourceAttribute primaryIdAttr = ShadowUtil.getAttribute(shadow, getPrimaryIdentifierAttributeQName()); - assertNotNull("No primary identifier (" + getPrimaryIdentifierAttributeQName() + " in " + shadow, primaryIdAttr); - String primaryId = primaryIdAttr.getRealValue(); - assertTrue("Unexpected chars in primary ID: '" + primaryId + "'", primaryId.matches("[a-z0-9\\-]+")); - - ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME)); - assertNotNull("No SID in " + shadow, objectSidAttr); - display("SID of " + dn + ": " + objectSidAttr); - } - - protected void assertSid(PrismObject shadow, String expectedSid) { - ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME)); - assertNotNull("No SID in " + shadow, objectSidAttr); - display("SID of " + shadow + ": " + objectSidAttr); - assertEquals("Wrong SID in " + shadow, expectedSid, objectSidAttr.getRealValue()); - } - - private void assertObjectCategory(PrismObject shadow, String expectedObjectCategory) { - ResourceAttribute objectCategoryAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_CATEGORY_NAME)); - assertNotNull("No objectCategory in " + shadow, objectCategoryAttr); - display("objectCategory of " + shadow + ": " + objectCategoryAttr); - assertEquals("Wrong objectCategory in " + shadow, expectedObjectCategory, objectCategoryAttr.getRealValue()); - } - - @Override - protected Entry assertLdapAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { - Entry entry = searchLdapAccount("(cn=" + cn + ")"); - assertAttribute(entry, "cn", cn); - assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); - return entry; - } - - protected Entry assertLdapSubAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { - Entry entry = searchLdapAccount(getSubLdapConnectionConfig(), "(cn=" + cn + ")"); - assertAttribute(entry, "cn", cn); - assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); - return entry; - } - - @Override - protected void assertNoLdapAccount(String uid) { - throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); - } - - protected void assertNoLdapAccount(String uid, String cn) throws LdapException, IOException, CursorException { - assertNoLdapAccount(null, uid, cn); - } - - protected void assertNoLdapSubAccount(String uid, String cn) throws LdapException, IOException, CursorException { - assertNoLdapAccount(getSubLdapConnectionConfig(), uid, cn); - } - - protected void assertNoLdapAccount(UserLdapConnectionConfig config, String uid, String cn) throws LdapException, IOException, CursorException { - LdapNetworkConnection connection = ldapConnect(config); - List entriesCn = ldapSearch(config, connection, "(cn=" + cn + ")"); - List entriesSamAccountName = ldapSearch(config, connection, "(sAMAccountName=" + uid + ")"); - ldapDisconnect(connection); - - assertEquals("Unexpected number of entries for cn=" + cn + ": " + entriesCn, 0, entriesCn.size()); - assertEquals("Unexpected number of entries for sAMAccountName=" + uid + ": " + entriesSamAccountName, 0, entriesSamAccountName.size()); - } - - @Override - protected String toAccountDn(String username) { - throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); - } - - @Override - protected String toAccountDn(String username, String fullName) { - return ("CN=" + fullName + "," + getPeopleLdapSuffix()); - } - - protected String toAccountSubDn(String username, String fullName) { - return ("CN=" + fullName + "," + getPeopleLdapSubSuffix()); - } - - @Override - protected Rdn toAccountRdn(String username, String fullName) { - try { - return new Rdn(new Ava("CN", fullName)); - } catch (LdapInvalidDnException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - protected String toOrgDn(String cn) { - return "ou=" + cn + "," + getOrgsLdapSuffix(); - } - - protected String toOrgGroupDn(String groupCn, String orgName) { - return "cn=" + groupCn + "," + toOrgDn(orgName); - } - - protected Entry assertLdapOrg(String orgName) throws LdapException, IOException, CursorException { - String dn = toOrgDn(orgName); - Entry entry = getLdapEntry(dn); - assertNotNull("No entry " + dn, entry); - assertAttribute(entry, "ou", orgName); - return entry; - } - - protected Entry assertNoLdapOrg(String orgName) throws LdapException, IOException, CursorException { - String dn = toOrgDn(orgName); - Entry entry = getLdapEntry(dn); - assertNull("Unexpected org entry " + entry, entry); - return entry; - } - - protected Entry assertLdapOrgGroup(String groupCn, String orgName) throws LdapException, IOException, CursorException { - String dn = toOrgGroupDn(groupCn, orgName); - Entry entry = getLdapEntry(dn); - assertNotNull("No entry " + dn, entry); - assertAttribute(entry, "cn", groupCn); - return entry; - } - - protected Entry assertNoLdapOrgGroup(String groupCn, String orgName) throws LdapException, IOException, CursorException { - String dn = toOrgGroupDn(groupCn, orgName); - Entry entry = getLdapEntry(dn); - assertNull("Unexpected org group entry " + entry, entry); - return entry; - } - - protected void assertLdapPassword(String uid, String fullName, String password) throws LdapException, IOException, CursorException { - assertLdapPassword(null, uid, fullName, password); - } - - protected void assertLdapPassword(UserLdapConnectionConfig config, String uid, String fullName, String password) throws LdapException, IOException, CursorException { - Entry entry = getLdapAccountByCn(config, fullName); - assertLdapPassword(config, entry, password); - } - - protected void assertLdapPassword(String uid, String password) { - throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); - } - - protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws SchemaException { - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName), - prismContext); - return query; - } - - @Override - protected Entry createAccountEntry(String uid, String cn, String givenName, String sn) throws LdapException { - byte[] password = encodePassword("Secret.123"); - Entry entry = new DefaultEntry(toAccountDn(uid, cn), - "objectclass", getLdapAccountObjectClass(), - ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, uid, - "cn", cn, - "givenName", givenName, - "sn", sn, - ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512", - ATTRIBUTE_UNICODE_PWD_NAME, password); - return entry; - } - - private byte[] encodePassword(String password) { - String quotedPassword = "\"" + password + "\""; - try { - return quotedPassword.getBytes("UTF-16LE"); - } catch (UnsupportedEncodingException e) { - throw new SystemException(e.getMessage(), e); - } - } - - public void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { - assertAttribute(shadow, new QName(getResourceNamespace(), attrName), expectedValues); - } - - public void assertAttribute(PrismObject shadow, QName attrQname, T... expectedValues) { - List actualValues = ShadowUtil.getAttributeValues(shadow, attrQname); - PrismAsserts.assertSets("attribute " + attrQname + " in " + shadow, actualValues, expectedValues); - } - - protected abstract void assertAccountDisabled(PrismObject shadow); - - protected abstract void assertAccountEnabled(PrismObject shadow); - -} +/* + * Copyright (c) 2015-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.testing.conntest.ad; + +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_CREDENTIALS_PASSWORD_VALUE; + +import java.io.File; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.util.Collection; +import java.util.List; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import com.evolveum.midpoint.prism.PrismProperty; +import com.evolveum.midpoint.util.exception.ObjectNotFoundException; + +import org.apache.commons.lang.StringUtils; +import org.apache.directory.api.ldap.model.cursor.CursorException; +import org.apache.directory.api.ldap.model.entry.DefaultEntry; +import org.apache.directory.api.ldap.model.entry.Entry; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; +import org.apache.directory.api.ldap.model.name.Ava; +import org.apache.directory.api.ldap.model.name.Rdn; +import org.apache.directory.ldap.client.api.LdapNetworkConnection; +import org.testng.AssertJUnit; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; + +import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; +import com.evolveum.midpoint.model.api.ModelExecuteOptions; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.query.ObjectPaging; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.prism.query.OrderDirection; +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.schema.SearchResultList; +import com.evolveum.midpoint.schema.SearchResultMetadata; +import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.schema.internals.InternalCounters; +import com.evolveum.midpoint.schema.processor.ResourceAttribute; +import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; +import com.evolveum.midpoint.schema.processor.ResourceSchema; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.schema.util.ObjectQueryUtil; +import com.evolveum.midpoint.schema.util.ShadowUtil; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.util.MidPointTestConstants; +import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.testing.conntest.AbstractLdapTest; +import com.evolveum.midpoint.testing.conntest.UserLdapConnectionConfig; +import com.evolveum.midpoint.util.MiscUtil; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.util.exception.SystemException; +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; + +/** + * @author semancik + */ +@Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) +public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest + implements AdTestMixin { + + protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ad-ldap-multidomain"); + + protected static final File ROLE_PIRATES_FILE = new File(TEST_DIR, "role-pirate.xml"); + protected static final String ROLE_PIRATES_OID = "5dd034e8-41d2-11e5-a123-001e8c717e5b"; + + protected static final File ROLE_SUBMISSIVE_FILE = new File(TEST_DIR, "role-submissive.xml"); + protected static final String ROLE_SUBMISSIVE_OID = "0c0c81b2-d0a1-11e5-b51e-0309a826745e"; + + protected static final File ROLE_META_ORG_FILE = new File(TEST_DIR, "role-meta-org.xml"); + protected static final String ROLE_META_ORG_OID = "f2ad0ace-45d7-11e5-af54-001e8c717e5b"; + + protected static final File ROLE_META_ORG_GROUP_FILE = new File(TEST_DIR, "role-meta-org-group.xml"); + protected static final String ROLE_META_ORG_GROUP_OID = "c5d3294a-0d8e-11e7-bd9d-ff848c2e7e3f"; + + protected static final String ACCOUNT_JACK_SAM_ACCOUNT_NAME = "jack"; + protected static final String ACCOUNT_JACK_SID = "S-1-5-21-3305462238-3617280118-659738602-4878"; + protected static final String ACCOUNT_JACK_FULL_NAME = "Jack Sparrow"; + protected static final String ACCOUNT_JACK_PASSWORD = "qwe.123"; + + protected static final String ACCOUNT_HT_UID = "ht"; + protected static final String ACCOUNT_HT_CN = "Herman Toothrot"; + protected static final String ACCOUNT_HT_GIVENNAME = "Herman"; + protected static final String ACCOUNT_HT_SN = "Toothrot"; + protected static final String ACCOUNT_HT_SN_MODIFIED = "Torquemeda Marley"; + + protected static final String ACCOUNT_HTM_UID = "htm"; + protected static final String ACCOUNT_HTM_CN = "Horatio Torquemada Marley"; + + protected static final String USER_CPTBARBOSSA_FULL_NAME = "Captain Hector Barbossa"; + + private static final String GROUP_PIRATES_NAME = "pirates"; + private static final String GROUP_MELEE_ISLAND_NAME = "Mêlée Island"; + private static final String GROUP_MELEE_ISLAND_ALT_NAME = "Alternative Mêlée Island"; + private static final String GROUP_MELEE_ISLAND_PIRATES_NAME = "Mêlée Island Pirates"; + private static final String GROUP_MELEE_ISLAND_PIRATES_DESCRIPTION = "swashbuckle and loot"; + + protected static final int NUMBER_OF_ACCOUNTS = 18; + private static final String ASSOCIATION_GROUP_NAME = "group"; + + private static final String NS_EXTENSION = "http://whatever.com/my"; + private static final QName EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME = new QName(NS_EXTENSION, "showInAdvancedViewOnly"); + + protected static final File USER_SUBMAN_FILE = new File(TEST_DIR, "user-subman.xml"); + private static final String USER_SUBMAN_OID = "910ac45a-8bd6-11e6-9122-ef88d95095f0"; + private static final String USER_SUBMAN_USERNAME = "subman"; + private static final String USER_SUBMAN_GIVEN_NAME = "Sub"; + private static final String USER_SUBMAN_FAMILY_NAME = "Man"; + private static final String USER_SUBMAN_FULL_NAME = "Sub Man"; + private static final String USER_SUBMAN_PASSWORD = "sub.123"; + + private static final String USER_SUBDOG_USERNAME = "subdog"; + private static final String USER_SUBDOG_GIVEN_NAME = "Sub"; + private static final String USER_SUBDOG_FAMILY_NAME = "Dog"; + private static final String USER_SUBDOG_FULL_NAME = "Sub Dog"; + + protected static final File USER_SUBMARINE_FILE = new File(TEST_DIR, "user-submarine.xml"); + private static final String USER_SUBMARINE_OID = "c4377f86-8be9-11e6-8ef5-c3c56ff64b09"; + private static final String USER_SUBMARINE_USERNAME = "submarine"; + private static final String USER_SUBMARINE_GIVEN_NAME = "Sub"; + private static final String USER_SUBMARINE_FAMILY_NAME = "Marine"; + private static final String USER_SUBMARINE_FULL_NAME = "Sub Marine"; + + private static final String INTENT_GROUP = "group"; + private static final String INTENT_OU_TOP = "ou-top"; + + private static final String USER_EMPTYHEAD_NAME = "emptyhead"; + + private static final String PROXY_ADDRES_ADDR_UPCASE = "smpt:ADDR"; + private static final String PROXY_ADDRES_ADDR_LOWCASE = "smpt:addr"; + + private static final String OBJECT_CATEGORY_PERSON = "CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com"; + private static final String OBJECT_CATEGORY_GROUP = "CN=Group,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com"; + + private static final String USER_GUYBRUSH_PASSWORD_123 = "wanna.be.a.123"; + private static final String USER_GUYBRUSH_PASSWORD_333 = "wanna.be.a.333"; + + private boolean allowDuplicateSearchResults = false; + + protected String jackAccountOid; + protected String groupPiratesOid; + protected long jackLockoutTimestamp; + protected String accountBarbossaOid; + protected String orgMeleeIslandOid; + protected String groupMeleeIslandOid; + protected String ouMeleeIslandOid; + protected String roleMeleeIslandPiratesOid; + protected String groupMeleeIslandPiratesOid; + + private String accountSubmanOid; + + private String accountSubmarineOid; + + @Override + public String getStartSystemCommand() { + return null; + } + + @Override + public String getStopSystemCommand() { + return null; + } + + @Override + protected File getBaseDir() { + return TEST_DIR; + } + + @Override + protected String getSyncTaskOid() { + return "0f93d8d4-5fb4-11ea-8571-a3f090bf921f"; + } + + @Override + protected boolean useSsl() { + return true; + } + + @Override + protected String getLdapSuffix() { + return "DC=ad,DC=evolveum,DC=com"; + } + + @Override + protected String getLdapBindDn() { + return "CN=midpoint,CN=Users,DC=ad,DC=evolveum,DC=com"; + } + + @Override + protected String getLdapBindPassword() { + return "qwe.123"; + } + + @Override + protected int getSearchSizeLimit() { + return -1; + } + + @Override + public String getPrimaryIdentifierAttributeName() { + return "objectGUID"; + } + + @Override + protected String getPeopleLdapSuffix() { + return "CN=Users," + getLdapSuffix(); + } + + @Override + protected String getGroupsLdapSuffix() { + return "CN=Users," + getLdapSuffix(); + } + + protected String getLdapSubSuffix() { + return "DC=sub,DC=ad,DC=evolveum,DC=com"; + } + + protected String getPeopleLdapSubSuffix() { + return "CN=Users," + getLdapSubSuffix(); + } + + @Override + protected String getLdapAccountObjectClass() { + return "user"; + } + + @Override + protected String getLdapGroupObjectClass() { + return "group"; + } + + @Override + protected String getLdapGroupMemberAttribute() { + return "member"; + } + + private QName getAssociationGroupQName() { + return new QName(MidPointConstants.NS_RI, ASSOCIATION_GROUP_NAME); + } + + @Override + protected boolean allowDuplicateSearchResults() { + return allowDuplicateSearchResults; + } + + @Override + protected boolean isGroupMemberMandatory() { + return false; + } + + protected String getOrgsLdapSuffix() { + return "OU=Org," + getLdapSuffix(); + } + + private UserLdapConnectionConfig getSubLdapConnectionConfig() { + UserLdapConnectionConfig config = new UserLdapConnectionConfig(); + config.setLdapHost("hydra.ad.evolveum.com"); + config.setLdapPort(getLdapServerPort()); + config.setBindDn("CN=midpoint,CN=Users,DC=sub,DC=ad,DC=evolveum,DC=com"); + config.setBindPassword(getLdapBindPassword()); + config.setBaseContext(getLdapSubSuffix()); + return config; + } + + protected abstract File getReconciliationTaskFile(); + + protected abstract String getReconciliationTaskOid(); + + protected String getLdapConnectorClassName() { + return AD_CONNECTOR_TYPE; + } + + @Override + public void initSystem(Task initTask, OperationResult initResult) throws Exception { + super.initSystem(initTask, initResult); + + binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_OBJECT_GUID_NAME); + binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_UNICODE_PWD_NAME); + + // Users + repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); + repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); + repoAddObjectFromFile(USER_SUBMAN_FILE, initResult); + repoAddObjectFromFile(USER_SUBMARINE_FILE, initResult); + + // Roles + repoAddObjectFromFile(ROLE_END_USER_FILE, initResult); + repoAddObjectFromFile(ROLE_PIRATES_FILE, initResult); + repoAddObjectFromFile(ROLE_SUBMISSIVE_FILE, initResult); + repoAddObjectFromFile(ROLE_META_ORG_FILE, initResult); + repoAddObjectFromFile(ROLE_META_ORG_GROUP_FILE, initResult); + + assignRole(USER_BARBOSSA_OID, ROLE_END_USER_OID); + + } + + @Test + public void test000Sanity() throws Exception { + assertLdapPassword(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME, ACCOUNT_JACK_PASSWORD); + cleanupDelete(toAccountDn(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME)); + cleanupDelete(toAccountDn(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME)); + cleanupDelete(toAccountDn(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME)); + cleanupDelete(getSubLdapConnectionConfig(), toAccountSubDn(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME)); + cleanupDelete(getSubLdapConnectionConfig(), toAccountSubDn(USER_SUBDOG_USERNAME, USER_SUBDOG_FULL_NAME)); + cleanupDelete(getSubLdapConnectionConfig(), toAccountSubDn(USER_SUBMARINE_USERNAME, USER_SUBMARINE_FULL_NAME)); + cleanupDelete(toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN)); + cleanupDelete(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN)); + cleanupDelete(toGroupDn(GROUP_MELEE_ISLAND_NAME)); + cleanupDelete(toGroupDn(GROUP_MELEE_ISLAND_ALT_NAME)); + cleanupDelete(toOrgGroupDn(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME)); + cleanupDelete(toOrgGroupDn(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME)); + cleanupDelete(toOrgDn(GROUP_MELEE_ISLAND_NAME)); + cleanupDelete("ou=underMelee," + toOrgDn(GROUP_MELEE_ISLAND_ALT_NAME)); + cleanupDelete(toOrgDn(GROUP_MELEE_ISLAND_ALT_NAME)); + } + + @Test + @Override + public void test020Schema() throws Exception { + // IntegrationTestTools.displayXml("Resource XML", resource); + accountObjectClassDefinition = assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); + assertAdRefinedSchema(resource, getAccountObjectClass()); + assertExchangeSchema(resource, getAccountObjectClass(), prismContext); + + ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); + assertEquals("Unexpected number of schema definitions (limited by generation constraints)", 5, resourceSchema.getDefinitions().size()); + + assertLdapConnectorInstances(1); + } + + @Test + public void test100SeachJackBySamAccountName() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = createSamAccountNameQuery(ACCOUNT_JACK_SAM_ACCOUNT_NAME); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + when(); + SearchResultList> shadows = + modelService.searchObjects(ShadowType.class, query, null, task, result); + + // THEN + then(); + assertSuccess(result); + + assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); + + PrismObject shadow = shadows.get(0); + display("Shadow", shadow); + assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); + assertSid(shadow, ACCOUNT_JACK_SID); + assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); + jackAccountOid = shadow.getOid(); + +// assertConnectorOperationIncrement(2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = shadows.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(1); + } + + /** + * MID-3730 + */ + @Test + public void test101SeachJackByDn() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + String jackDn = toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME); + ObjectQuery query = createAccountShadowQueryByAttribute("dn", jackDn, resource); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + when(); + SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); + + // THEN + then(); + assertSuccess(result); + + assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); + + PrismObject shadow = shadows.get(0); + display("Shadow", shadow); + assertAccountShadow(shadow, jackDn); + assertSid(shadow, ACCOUNT_JACK_SID); + assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); + +// assertConnectorOperationIncrement(2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = shadows.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(1); + } + + /** + * Search for non-existent DN should return no results. It should NOT + * throw an error. + *

+ * MID-3730 + */ + @Test + public void test102SeachNotExistByDn() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + String dn = toAccountDn("idonoexist", "I am a Fiction"); + ObjectQuery query = createAccountShadowQueryByAttribute("dn", dn, resource); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + when(); + SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); + + // THEN + then(); + assertSuccess(result); + + assertEquals("Unexpected search result: " + shadows, 0, shadows.size()); + +// assertConnectorOperationIncrement(2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + assertLdapConnectorInstances(1); + } + + @Test + public void test105SeachPiratesByCn() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); + ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_PIRATES_NAME), prismContext); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + when(); + SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); + + // THEN + then(); + assertSuccess(result); + + assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); + + PrismObject shadow = shadows.get(0); + display("Shadow", shadow); + groupPiratesOid = shadow.getOid(); + assertObjectCategory(shadow, OBJECT_CATEGORY_GROUP); + +// assertConnectorOperationIncrement(1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = shadows.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(1); + } + + @Test + public void test110GetJack() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + long startOfTestMsTimestamp = getWin32Filetime(System.currentTimeMillis()); + + // WHEN + when(); + PrismObject shadow = modelService.getObject(ShadowType.class, jackAccountOid, null, task, result); + + // THEN + then(); + assertSuccess(result); + + display("Shadow", shadow); + assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); + jackAccountOid = shadow.getOid(); + + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + + assertAttribute(shadow, "dn", "CN=Jack Sparrow,CN=Users,DC=ad,DC=evolveum,DC=com"); + assertAttribute(shadow, "cn", ACCOUNT_JACK_FULL_NAME); + assertAttribute(shadow, "sn", "Sparrow"); + assertAttribute(shadow, "description", "The best pirate the world has ever seen"); + assertAttribute(shadow, "sAMAccountName", ACCOUNT_JACK_SAM_ACCOUNT_NAME); + assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); + List lastLogonValues = ShadowUtil.getAttributeValues(shadow, new QName(getResourceNamespace(), "lastLogon")); + assertEquals("Wrong number of lastLong values: " + lastLogonValues, 1, lastLogonValues.size()); + if (lastLogonValues.get(0) > startOfTestMsTimestamp) { + fail("Wrong lastLogon, expected it to be less than " + startOfTestMsTimestamp + ", but was " + lastLogonValues.get(0)); + } + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + assertLdapConnectorInstances(1); + } + + /** + * No paging. It should return all accounts. + */ + @Test + public void test150SeachAllAccounts() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + SearchResultList> searchResultList = doSearch(query, + NUMBER_OF_ACCOUNTS, task, result); + + // TODO: Why 14? Why not 1? + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 14); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * This is in one block. + */ + @Test + public void test152SeachFirst2Accounts() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(); + paging.setMaxSize(2); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 2, task, result); + + // TODO: Why 2? Why not 1? + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + @Test + public void test154SeachFirst11Accounts() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(); + paging.setMaxSize(11); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 11, task, result); + + // TODO: Why 2? Why not 1? + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + @Test + public void test162SeachFirst2AccountsOffset0() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(); + paging.setOffset(0); + paging.setMaxSize(2); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 2, task, result); + + // TODO: Why 2? Why not 1? + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * There is offset, so VLV should be used. + * No explicit sorting. + */ + @Test + public void test172Search2AccountsOffset1() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 2, task, result); + + // TODO: Why 2? Why not 1? + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * There is offset, so VLV should be used. + * No explicit sorting. + */ + @Test + public void test174SeachFirst11AccountsOffset2() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(2, 11); + query.setPaging(paging); + + allowDuplicateSearchResults = true; + + // WHEN + SearchResultList> searchResultList = doSearch(query, 11, task, result); + + // THEN + allowDuplicateSearchResults = false; + + // TODO: Why 2? Why not 1? + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * There is offset, so VLV should be used. + * Explicit sorting. + */ + @Test + public void test182Search2AccountsOffset1SortCn() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); + paging.setOrdering(getAttributePath(resource, "cn"), OrderDirection.ASCENDING); + query.setPaging(paging); + + SearchResultList> shadows = doSearch(query, 2, task, result); + + assertAccountShadow(shadows.get(0), "CN=Adolf Supperior,CN=Users,DC=ad,DC=evolveum,DC=com"); +// assertAccountShadow(shadows.get(1), "CN=DiscoverySearchMailbox {D919BA05-46A6-415f-80AD-7E09334BB852},CN=Users,DC=ad,DC=evolveum,DC=com"); + + // TODO: Why 2? Why not 1? + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = shadows.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + @Test + public void test200AssignAccountBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + assignAccountToUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "title", null); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getShadowModel(shadowOid); + display("Shadow (model)", shadow); + accountBarbossaOid = shadow.getOid(); + Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); + String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); + assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); + + assertEquals("Wrong ICFS UID", + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + accountBarbossaIcfUid); + + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + + // MID-4624 + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); + assertNotNull("No createTimestamp in " + shadow, createTimestampAttribute); + XMLGregorianCalendar createTimestamp = createTimestampAttribute.getRealValue(); + long createTimestampMillis = XmlTypeConverter.toMillis(createTimestamp); + // LDAP server may be on a different host. Allow for some clock offset. + TestUtil.assertBetween("Wrong createTimestamp in " + shadow, roundTsDown(tsStart) - 120000, roundTsUp(tsEnd) + 120000, createTimestampMillis); + + assertObjectCategory(shadow, OBJECT_CATEGORY_PERSON); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test210ModifyAccountBarbossaTitle() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, ATTRIBUTE_TITLE_NAME); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); + delta.addModification(attrDelta); + + // WHEN + when(); + executeChanges(delta, null, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_TITLE_NAME, "Captain"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); + delta.addModification(attrDelta); + + // WHEN + when(); + executeChanges(delta, null, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "showInAdvancedViewOnly", "TRUE"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapConnectorInstances(2); + } + + /** + * Modify USER, test boolean value mapping. + */ + @Test + public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); + delta.addModification(attrDelta); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, ItemPath.create(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), + task, result, Boolean.FALSE); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "showInAdvancedViewOnly", "FALSE"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapConnectorInstances(2); + } + + /** + * Just normal modification of proxyAddress, directly on the account. + * As proxyAddress is multivalue, this is ADD and not REPLACE. This is what GUI would do. + * No previous value for proxyAddress is set in the AD account. + * MID-5330 + */ + @Test + public void test214ModifyAccountBarbossaProxyAddressesSimple() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, ATTRIBUTE_PROXY_ADDRESSES_NAME); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + assertNotNull("No definition for attribute " + attrQName, attrDef); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationAddProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, PROXY_ADDRES_ADDR_UPCASE); + delta.addModification(attrDelta); + + // WHEN + when(); + executeChanges(delta, null, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_PROXY_ADDRESSES_NAME, PROXY_ADDRES_ADDR_UPCASE); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test220ModifyUserBarbossaPasswordSelfServicePassword1() throws Exception { + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD, USER_BARBOSSA_PASSWORD_AD_1); + } + + /** + * Try to set the same password again. If this is "admin mode" (no runAs capability) + * the such change should be successful. In "selfservice mode" (runAs capability - in subclass) + * this change should fail. + */ + @Test + public void test222ModifyUserBarbossaPasswordSelfServicePassword1Again() throws Exception { + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_1); + } + + /** + * Change to different password. This should go well for both admin and self-service. + * MID-5242 + */ + @Test + public void test224ModifyUserBarbossaPasswordSelfServicePassword2() throws Exception { + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD_AD_1, USER_BARBOSSA_PASSWORD_AD_2); + } + + /** + * Change password back to the first password. This password was used before. + * In admin mode this should go well. Admin can set password to anything. + * But in self-service mode (in subclass) this should fail due to password history check. + */ + @Test + public void test226ModifyUserBarbossaPasswordSelfServicePassword1AgainAgain() throws Exception { + testModifyUserBarbossaPasswordSelfServiceSuccess( + USER_BARBOSSA_PASSWORD_AD_2, USER_BARBOSSA_PASSWORD_AD_1); + } + + protected void testModifyUserBarbossaPasswordSelfServiceSuccess(String oldPassword, String newPassword) throws Exception { + // GIVEN + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, oldPassword); + + login(USER_BARBOSSA_USERNAME); + + Task task = getTestTask(); + task.setChannel(SchemaConstants.CHANNEL_GUI_SELF_SERVICE_URI); + OperationResult result = task.getResult(); + + ObjectDelta objectDelta = createOldNewPasswordDelta(USER_BARBOSSA_OID, + oldPassword, newPassword); + + // WHEN + when(); + executeChanges(objectDelta, null, task, result); + + // THEN + then(); + login(USER_ADMINISTRATOR_USERNAME); + assertSuccess(result); + + assertBarbossaEnabled(newPassword); + + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, newPassword); + + assertLdapConnectorInstances(2); + } + + protected void testModifyUserBarbossaPasswordSelfServiceFailure( + String oldPassword, String newPassword) throws Exception { + // GIVEN + login(USER_BARBOSSA_USERNAME); + + Task task = getTestTask(); + task.setChannel(SchemaConstants.CHANNEL_GUI_SELF_SERVICE_URI); + OperationResult result = task.getResult(); + + ObjectDelta objectDelta = createOldNewPasswordDelta(USER_BARBOSSA_OID, + oldPassword, newPassword); + + // WHEN + when(); + executeChanges(objectDelta, null, task, result); + + // THEN + then(); + login(USER_ADMINISTRATOR_USERNAME); + assertPartialError(result); + + assertBarbossaEnabled(newPassword); + assertUserAfter(USER_BARBOSSA_OID) + .assertPassword(newPassword); + + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, oldPassword); + + assertLdapConnectorInstances(2); + } + + @Test + public void test230DisableUserBarbossa() throws Exception { + // precondition + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); + + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + task, result, ActivationStatusType.DISABLED); + + // THEN + then(); + assertSuccess(result); + + assertBarbossaDisabled(USER_BARBOSSA_PASSWORD_AD_1); + } + + /** + * MID-4041 + */ + @Test + public void test232ReconcileBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + reconcileUser(USER_BARBOSSA_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + assertBarbossaDisabled(USER_BARBOSSA_PASSWORD_AD_1); + } + + /** + * MID-4041 + */ + @Test + public void test236EnableUserBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + task, result, ActivationStatusType.ENABLED); + + // THEN + then(); + assertSuccess(result); + + assertBarbossaEnabled(USER_BARBOSSA_PASSWORD_AD_1); + + assertLdapConnectorInstances(2); + } + + /** + * MID-4041 + */ + @Test + public void test237ReconcileBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + reconcileUser(USER_BARBOSSA_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + assertBarbossaEnabled(USER_BARBOSSA_PASSWORD_AD_1); + + assertLdapConnectorInstances(2); + } + + /** + * MID-4041 + */ + @Test + public void test238DisableUserBarbossaRawAndReconcile() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + modifyUserReplace(USER_BARBOSSA_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + ModelExecuteOptions.createRaw(), task, result, ActivationStatusType.DISABLED); + + // WHEN + when(); + reconcileUser(USER_BARBOSSA_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + assertBarbossaDisabled(USER_BARBOSSA_PASSWORD_AD_1); + + assertLdapConnectorInstances(2); + } + + /** + * MID-4041 + */ + @Test + public void test239EnableUserBarbossaRawAndReconcile() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + modifyUserReplace(USER_BARBOSSA_OID, SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + ModelExecuteOptions.createRaw(), task, result, ActivationStatusType.ENABLED); + + // WHEN + when(); + reconcileUser(USER_BARBOSSA_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + assertBarbossaEnabled(USER_BARBOSSA_PASSWORD_AD_1); + + assertLdapConnectorInstances(2); + } + + protected PrismObject assertBarbossaEnabled(String ldapPassword) throws Exception { + PrismObject user = getUser(USER_BARBOSSA_OID); + assertAdministrativeStatus(user, ActivationStatusType.ENABLED); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "title", "Captain"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "FALSE"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountEnabled(shadow); + + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, ldapPassword); + + return user; + } + + private void assertBarbossaDisabled(String password) throws Exception { + assertLdapConnectorInstances(2); + + PrismObject user = getUser(USER_BARBOSSA_OID); + assertAdministrativeStatus(user, ActivationStatusType.DISABLED); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + display("disabled Barbossa entry", entry); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + + assertAttribute(entry, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME, "TRUE"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountDisabled(shadow); + + try { + assertLdapPassword(null, entry, password); + AssertJUnit.fail("Password authentication works, but it should fail"); + } catch (SecurityException e) { + // this is expected + } + + assertLdapConnectorInstances(2); + } + + /** + * This should create account with a group. And the account shoudl be disabled. + */ + @Test + public void test250AssignGuybrushPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + +// ProtectedStringType userPasswordPs = new ProtectedStringType(); +// userPasswordPs.setClearValue(USER_GUYBRUSH_PASSWORD_333); +// modifyUserReplace(USER_GUYBRUSH_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); + modifyUserReplace(USER_GUYBRUSH_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + task, result, ActivationStatusType.DISABLED); + + // WHEN + when(); + assignRole(USER_GUYBRUSH_OID, ROLE_PIRATES_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + display("Entry", entry); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + + assertLdapGroupMember(entry, GROUP_PIRATES_NAME); + + PrismObject user = getUser(USER_GUYBRUSH_OID); + assertAdministrativeStatus(user, ActivationStatusType.DISABLED); + String shadowOid = getSingleLinkOid(user); + + PrismObject shadow = getObject(ShadowType.class, shadowOid); + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + assertAccountDisabled(shadow); + +// try { +// assertLdapPassword(null, entry, USER_GUYBRUSH_PASSWORD_333); +// AssertJUnit.fail("Password authentication works, but it should fail"); +// } catch (SecurityException e) { +// // this is expected, account is disabled +// } + + assertLdapConnectorInstances(2); + } + + @Test + public void test255ModifyUserGuybrushPassword() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ProtectedStringType userPasswordPs = new ProtectedStringType(); + userPasswordPs.setClearValue(USER_GUYBRUSH_PASSWORD_123); + + // WHEN + when(); + modifyUserReplace(USER_GUYBRUSH_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + display("Guybrush entry after", entry); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + + try { + assertLdapPassword(null, entry, USER_GUYBRUSH_PASSWORD_123); + AssertJUnit.fail("Password authentication works, but it should fail"); + } catch (SecurityException e) { + // this is expected, account is disabled + } + +// assertLdapConnectorInstances(2); + } + + @Test + public void test260EnableGyubrush() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_GUYBRUSH_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + task, result, ActivationStatusType.ENABLED); + + // THEN + then(); + assertSuccess(result); + + PrismObject user = getUser(USER_GUYBRUSH_OID); + assertAdministrativeStatus(user, ActivationStatusType.ENABLED); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountEnabled(shadow); + + assertLdapPassword(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); + + assertLdapConnectorInstances(2); + } + + /** + * Try to create an account without password. This should end up with an error. + * A reasonable error. + * MID-4046 + */ + @Test + public void test270AssignAccountToEmptyhead() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + PrismObject userBefore = createUser(USER_EMPTYHEAD_NAME, USER_EMPTYHEAD_NAME, true); + display("User before", userBefore); + addObject(userBefore); + String userEmptyheadOid = userBefore.getOid(); + + // WHEN + when(); + assignAccountToUser(userEmptyheadOid, getResourceOid(), null, task, result); + + // THEN + then(); + assertPartialError(result); + + assertMessageContains(result.getMessage(), "does not meet the length, complexity, or history requirement"); + + assertLdapConnectorInstances(2); + } + + /** + * Just make random test connection between the tests. Make sure that the + * test does not break anything. If it does the next tests will simply fail. + */ + @Test + public void test295TestConnection() throws Exception { + // GIVEN + Task task = getTestTask(); + + // WHEN + when(); + OperationResult testResult = modelService.testResource(getResourceOid(), task); + + // THEN + then(); + display("Test connection result", testResult); + TestUtil.assertSuccess("Test connection result", testResult); + + // Test is disposing connector facade and the entire connector pool. + // Therefore we are back at 1 instance. + assertLdapConnectorInstances(1); + } + + @Test + public void test300AssignBarbossaPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + assignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + display("Entry", entry); + assertAttribute(entry, "title", "Captain"); + + assertLdapGroupMember(entry, GROUP_PIRATES_NAME); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + PrismObject shadow = getObject(ShadowType.class, shadowOid); + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + + assertLdapConnectorInstances(1); + } + + @Test + public void test390ModifyUserBarbossaRename() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_BARBOSSA_OID, UserType.F_NAME, + PrismTestUtil.createPolyString(USER_CPTBARBOSSA_USERNAME)); + objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, + PrismTestUtil.createPolyString(USER_CPTBARBOSSA_FULL_NAME)); + Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); + + // WHEN + when(); + modelService.executeChanges(deltas, null, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); + assertAttribute(entry, "title", "Captain"); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + display("Shadow after rename (model)", shadow); + + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); + display("Shadow after rename (repo)", repoShadow); + + assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + +// assertLdapConnectorInstances(2); + } + + // TODO: create account with a group membership + + @Test + public void test395UnAssignBarbossaPirates() throws Exception { + // TODO: do this on another account. There is a bad interference with rename. + + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + unassignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); + display("Entry", entry); + assertAttribute(entry, "title", "Captain"); + + assertLdapNoGroupMember(entry, GROUP_PIRATES_NAME); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + PrismObject shadow = getObject(ShadowType.class, shadowOid); + IntegrationTestTools.assertNoAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test399UnAssignAccountBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + unassignAccountFromUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertNoLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); + + PrismObject user = getUser(USER_BARBOSSA_OID); + assertNoLinkedAccount(user); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test500AddOrgMeleeIsland() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + PrismObject org = instantiateObject(OrgType.class); + OrgType orgType = org.asObjectable(); + orgType.setName(new PolyStringType(GROUP_MELEE_ISLAND_NAME)); + AssignmentType metaroleAssignment = new AssignmentType(); + ObjectReferenceType metaroleRef = new ObjectReferenceType(); + metaroleRef.setOid(ROLE_META_ORG_OID); + metaroleRef.setType(RoleType.COMPLEX_TYPE); + metaroleAssignment.setTargetRef(metaroleRef); + orgType.getAssignment().add(metaroleAssignment); + + // WHEN + when(); + addObject(org, task, result); + + // THEN + then(); + assertSuccess(result); + + orgMeleeIslandOid = org.getOid(); + assertLdapGroup(GROUP_MELEE_ISLAND_NAME); + assertLdapOrg(GROUP_MELEE_ISLAND_NAME); + + org = getObject(OrgType.class, orgMeleeIslandOid); + groupMeleeIslandOid = getLinkRefOid(org, getResourceOid(), ShadowKindType.ENTITLEMENT, INTENT_GROUP); + ouMeleeIslandOid = getLinkRefOid(org, getResourceOid(), ShadowKindType.GENERIC, INTENT_OU_TOP); + assertLinks(org, 2); + + PrismObject shadowGroup = getShadowModel(groupMeleeIslandOid); + display("Shadow: group (model)", shadowGroup); + + PrismObject shadowOu = getShadowModel(ouMeleeIslandOid); + display("Shadow: ou (model)", shadowOu); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test510AssignGuybrushMeleeIsland() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + assignOrg(USER_GUYBRUSH_OID, orgMeleeIslandOid, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + + PrismObject user = getUser(USER_GUYBRUSH_OID); + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getShadowModel(shadowOid); + display("Shadow (model)", shadow); + + assertLdapGroupMember(entry, GROUP_MELEE_ISLAND_NAME); + + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupMeleeIslandOid); + +// assertLdapConnectorInstances(2); + } + + /** + * Create role under the Melee Island org. This creates group in the orgstruct. + */ + @Test + public void test515AddOrgGroupMeleeIslandPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + PrismObject role = instantiateObject(RoleType.class); + RoleType roleType = role.asObjectable(); + roleType.setName(new PolyStringType(GROUP_MELEE_ISLAND_PIRATES_NAME)); + + AssignmentType metaroleAssignment = new AssignmentType(); + ObjectReferenceType metaroleRef = new ObjectReferenceType(); + metaroleRef.setOid(ROLE_META_ORG_GROUP_OID); + metaroleRef.setType(RoleType.COMPLEX_TYPE); + metaroleAssignment.setTargetRef(metaroleRef); + roleType.getAssignment().add(metaroleAssignment); + + AssignmentType orgAssignment = new AssignmentType(); + ObjectReferenceType orgRef = new ObjectReferenceType(); + orgRef.setOid(orgMeleeIslandOid); + orgRef.setType(OrgType.COMPLEX_TYPE); + orgAssignment.setTargetRef(orgRef); + roleType.getAssignment().add(orgAssignment); + + // WHEN + when(); + addObject(role, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + roleMeleeIslandPiratesOid = role.getOid(); + // TODO: assert LDAP object + + assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); + + PrismObject roleAfter = getObject(RoleType.class, roleMeleeIslandPiratesOid); + display("Role after", roleAfter); + groupMeleeIslandPiratesOid = getSingleLinkOid(roleAfter); + PrismObject shadow = getShadowModel(groupMeleeIslandPiratesOid); + display("Shadow (model)", shadow); + } + + /** + * Rename org unit. MidPoint should rename OU and ordinary group. + * AD will rename the group in the orgstruct automatically. We need to + * make sure that we can still access that group. + */ + @Test + public void test520RenameMeleeIsland() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + renameObject(OrgType.class, orgMeleeIslandOid, GROUP_MELEE_ISLAND_ALT_NAME, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + PrismObject orgAfter = getObject(OrgType.class, orgMeleeIslandOid); + groupMeleeIslandOid = getLinkRefOid(orgAfter, getResourceOid(), ShadowKindType.ENTITLEMENT, INTENT_GROUP); + ouMeleeIslandOid = getLinkRefOid(orgAfter, getResourceOid(), ShadowKindType.GENERIC, INTENT_OU_TOP); + assertLinks(orgAfter, 2); + + PrismObject shadowGroup = getShadowModel(groupMeleeIslandOid); + display("Shadow: group (model)", shadowGroup); + + PrismObject shadowOu = getShadowModel(ouMeleeIslandOid); + display("Shadow: ou (model)", shadowOu); + + assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); + assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); + + assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); + assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); + + assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); + assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); + + Entry entryGuybrush = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + + PrismObject user = getUser(USER_GUYBRUSH_OID); + String shadowAccountOid = getSingleLinkOid(user); + PrismObject shadowAccount = getShadowModel(shadowAccountOid); + display("Shadow: account (model)", shadowAccount); + + assertLdapGroupMember(entryGuybrush, GROUP_MELEE_ISLAND_ALT_NAME); + + IntegrationTestTools.assertAssociation(shadowAccount, getAssociationGroupQName(), groupMeleeIslandOid); + +// assertLdapConnectorInstances(2); + } + + /** + * AD renamed the pirate groups by itself. MidPoint does not know about it. + * The GUID that is stored in the shadow is still OK. But the DN is now out + * of date. Try to update the group. Make sure it works. + * It is expected that the GUI will be used as a primary identifier. + * Note: just reading the group will NOT work. MidPoint is too smart + * for that. It will transparently fix the situation. + */ + @Test + public void test522ModifyMeleeIslandPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyObjectReplaceProperty(ShadowType.class, groupMeleeIslandPiratesOid, + ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(MidPointConstants.NS_RI, "description")), + task, result, GROUP_MELEE_ISLAND_PIRATES_DESCRIPTION); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); + assertAttribute(entryOrgGroup, "description", GROUP_MELEE_ISLAND_PIRATES_DESCRIPTION); + + assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test524GetMeleeIslandPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + PrismObject shadow = modelService.getObject(ShadowType.class, groupMeleeIslandPiratesOid, null, task, result); + + // THEN + then(); + assertSuccess(result); + + display("Shadow after", shadow); + assertNotNull(shadow); + + assertLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); + assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); + assertLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); + assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); + Entry entryOrgGroup = assertLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); + display("Melee org", entryOrgGroup); + assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); + } + + @Test + public void test595DeleteOrgGroupMeleeIslandPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + deleteObject(RoleType.class, roleMeleeIslandPiratesOid, task, result); + + // THEN + then(); + assertSuccess(result); + + assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_ALT_NAME); + assertNoLdapOrgGroup(GROUP_MELEE_ISLAND_PIRATES_NAME, GROUP_MELEE_ISLAND_NAME); + + assertNoObject(ShadowType.class, groupMeleeIslandPiratesOid); + +// assertLdapConnectorInstances(2); + } + + /** + * We create "underMelee" org that gets into the way of the delete. + * Melee cannot be deleted in an ordinary way. "tree delete" control must + * be used. This is configured in the connector config. + *

+ * MID-5935 + */ + @Test + public void test599DeleteOrgMeleeIsland() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + createUnderMeleeEntry(); + + // WHEN + when(); + deleteObject(OrgType.class, orgMeleeIslandOid, task, result); + + // THEN + then(); + assertSuccess(result); + + assertNoLdapGroup(GROUP_MELEE_ISLAND_NAME); + assertNoLdapGroup(GROUP_MELEE_ISLAND_ALT_NAME); + assertNoLdapOrg(GROUP_MELEE_ISLAND_NAME); + assertNoLdapOrg(GROUP_MELEE_ISLAND_ALT_NAME); + + assertNoObject(ShadowType.class, groupMeleeIslandOid); + assertNoObject(ShadowType.class, ouMeleeIslandOid); + +// assertLdapConnectorInstances(2); + } + + protected void createUnderMeleeEntry() throws LdapException, IOException { + // This OU just gets into the way of the delete. + Entry entry = new DefaultEntry("ou=underMelee," + toOrgDn(GROUP_MELEE_ISLAND_ALT_NAME), + "objectclass", "organizationalUnit", + "ou", "underMelee"); + display("underMelee org", entry); + addLdapEntry(entry); + } + + @Test + public void test600AssignAccountSubman() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + assignRole(USER_SUBMAN_OID, ROLE_SUBMISSIVE_OID, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); + display("Sub entry", entry); + assertAttribute(entry, "title", null); + + PrismObject userAfter = getUser(USER_SUBMAN_OID); + String shadowOid = getSingleLinkOid(userAfter); + PrismObject shadow = getShadowModel(shadowOid); + display("Shadow (model)", shadow); + accountSubmanOid = shadow.getOid(); + Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); + String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); + assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); + + assertEquals("Wrong ICFS UID", + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + accountBarbossaIcfUid); + + assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, USER_SUBMAN_PASSWORD); + + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + // MID-4624 + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); + assertNotNull("No createTimestamp in " + shadow, createTimestampAttribute); + XMLGregorianCalendar createTimestamp = createTimestampAttribute.getRealValue(); + long createTimestampMillis = XmlTypeConverter.toMillis(createTimestamp); + // LDAP server may be on a different host. Allow for some clock offset. + TestUtil.assertBetween("Wrong createTimestamp in " + shadow, roundTsDown(tsStart) - 120000, roundTsUp(tsEnd) + 120000, createTimestampMillis); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test610ModifyUserSubmanTitle() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_SUBMAN_OID, UserType.F_TITLE, task, result, + createPolyString("Underdog")); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); + display("Sub entry", entry); + assertAttribute(entry, "title", "Underdog"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + PrismObject user = getUser(USER_SUBMAN_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountSubmanOid, shadowOid); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test620ModifyUserSubmanPassword() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ProtectedStringType userPasswordPs = new ProtectedStringType(); + userPasswordPs.setClearValue("SuB.321"); + + // WHEN + when(); + modifyUserReplace(USER_SUBMAN_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); + assertAttribute(entry, "title", "Underdog"); + assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, "SuB.321"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + PrismObject user = getUser(USER_SUBMAN_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountSubmanOid, shadowOid); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test630DisableUserSubman() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_SUBMAN_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + task, result, ActivationStatusType.DISABLED); + + // THEN + then(); + assertSuccess(result); + +// assertLdapConnectorInstances(2); + + PrismObject user = getUser(USER_SUBMAN_OID); + assertAdministrativeStatus(user, ActivationStatusType.DISABLED); + + Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountDisabled(shadow); + + try { + assertLdapPassword(getSubLdapConnectionConfig(), USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME, "SuB.321"); + AssertJUnit.fail("Password authentication works, but it should fail"); + } catch (SecurityException e) { + // this is expected + } + +// assertLdapConnectorInstances(2); + } + + @Test + public void test639EnableUserSubman() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_SUBMAN_OID, + SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS, + task, result, ActivationStatusType.ENABLED); + + // THEN + then(); + assertSuccess(result); + + PrismObject user = getUser(USER_SUBMAN_OID); + assertAdministrativeStatus(user, ActivationStatusType.ENABLED); + + Entry entry = assertLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountEnabled(shadow); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test690ModifyUserSubmanRename() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_SUBMAN_OID, UserType.F_NAME, + createPolyString(USER_SUBDOG_USERNAME)); + objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, + createPolyString(USER_SUBDOG_FULL_NAME)); + + // WHEN + when(); + executeChanges(objectDelta, null, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapSubAccount(USER_SUBDOG_USERNAME, USER_SUBDOG_FULL_NAME); + assertAttribute(entry, "title", "Underdog"); + + PrismObject user = getUser(USER_SUBMAN_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountSubmanOid, shadowOid); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + display("Shadow after rename (model)", shadow); + + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); + display("Shadow after rename (repo)", repoShadow); + + assertNoLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); + +// assertLdapConnectorInstances(2); + } + + @Test + public void test699UnAssignAccountSubdog() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + unassignRole(USER_SUBMAN_OID, ROLE_SUBMISSIVE_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + assertNoLdapSubAccount(USER_SUBMAN_USERNAME, USER_SUBMAN_FULL_NAME); + assertNoLdapSubAccount(USER_SUBDOG_USERNAME, USER_SUBDOG_FULL_NAME); + + PrismObject user = getUser(USER_SUBMAN_OID); + assertNoLinkedAccount(user); + +// assertLdapConnectorInstances(2); + } + + /** + * Create account and modify it in a very quick succession. + * This test is designed to check if we can live with a long + * global catalog update delay. + * MID-2926 + */ + @Test + public void test700AssignAccountSubmarineAndModify() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + assignRole(USER_SUBMARINE_OID, ROLE_SUBMISSIVE_OID, task, result); + + modifyUserReplace(USER_SUBMARINE_OID, UserType.F_TITLE, task, result, + PrismTestUtil.createPolyString("Underseadog")); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapSubAccount(USER_SUBMARINE_USERNAME, USER_SUBMARINE_FULL_NAME); + display("Sub entry", entry); + assertAttribute(entry, "title", "Underseadog"); + + PrismObject userAfter = getUser(USER_SUBMARINE_OID); + String shadowOid = getSingleLinkOid(userAfter); + PrismObject shadow = getShadowModel(shadowOid); + display("Shadow (model)", shadow); + accountSubmarineOid = shadow.getOid(); + Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); + String accountIcfUid = (String) identifiers.iterator().next().getRealValue(); + assertNotNull("No identifier in " + shadow, accountIcfUid); + + assertEquals("Wrong ICFS UID", + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + accountIcfUid); + + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + } + + @Test + public void test809UnAssignAccountSubmarine() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + unassignRole(USER_SUBMARINE_OID, ROLE_SUBMISSIVE_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + assertNoLdapSubAccount(USER_SUBMARINE_USERNAME, USER_SUBMARINE_FULL_NAME); + + PrismObject user = getUser(USER_SUBMARINE_OID); + assertNoLinkedAccount(user); + } + + @Test + public void test850ReconcileAccounts() throws Exception { + // GIVEN + assertUsers(6); + + // WHEN + when(); + addTask(getReconciliationTaskFile()); + + waitForTaskFinish(getReconciliationTaskOid(), true); + + // THEN + then(); + + assertUsers(15); + // TODO + +// assertLdapConnectorInstances(2); + } + + @Test + public void test900ImportSyncTask() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + addObject(getSyncTaskFile(), task, result); + + // THEN + then(); + assertSuccess(result); + + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + long tsEnd = System.currentTimeMillis(); + + assertStepSyncToken(getSyncTaskOid(), 0, tsStart, tsEnd); + } + + @Test + public void test901SyncAddAccountHt() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + addLdapAccount(ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); + waitForTaskNextRunAssertSuccess(getSyncTaskOid(), true); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + displayUsers(); + + PrismObject user = findUserByUsername(ACCOUNT_HT_UID); + assertNotNull("No user " + ACCOUNT_HT_UID + " created", user); + assertUser(user, user.getOid(), ACCOUNT_HT_UID, ACCOUNT_HT_CN, ACCOUNT_HT_GIVENNAME, ACCOUNT_HT_SN); + + assertStepSyncToken(getSyncTaskOid(), 1, tsStart, tsEnd); + } + + protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) + throws ObjectNotFoundException, SchemaException { + OperationResult result = createOperationResult("assertStepSyncToken"); + Task task = taskManager.getTask(syncTaskOid, result); + PrismProperty syncTokenProperty = task.getExtensionPropertyOrClone(SchemaConstants.SYNC_TOKEN); + assertNotNull("No sync token", syncTokenProperty); + assertNotNull("No sync token value", syncTokenProperty.getRealValue()); + assertNotNull("Empty sync token value", StringUtils.isBlank(syncTokenProperty.getRealValue())); + assertSuccess(result); + } + + @Override + protected void assertAccountShadow(PrismObject shadow, String dn) throws SchemaException { + super.assertAccountShadow(shadow, dn); + ResourceAttribute primaryIdAttr = ShadowUtil.getAttribute(shadow, getPrimaryIdentifierAttributeQName()); + assertNotNull("No primary identifier (" + getPrimaryIdentifierAttributeQName() + " in " + shadow, primaryIdAttr); + String primaryId = primaryIdAttr.getRealValue(); + assertTrue("Unexpected chars in primary ID: '" + primaryId + "'", primaryId.matches("[a-z0-9\\-]+")); + + ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME)); + assertNotNull("No SID in " + shadow, objectSidAttr); + display("SID of " + dn + ": " + objectSidAttr); + } + + protected void assertSid(PrismObject shadow, String expectedSid) { + ResourceAttribute objectSidAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME)); + assertNotNull("No SID in " + shadow, objectSidAttr); + display("SID of " + shadow + ": " + objectSidAttr); + assertEquals("Wrong SID in " + shadow, expectedSid, objectSidAttr.getRealValue()); + } + + private void assertObjectCategory(PrismObject shadow, String expectedObjectCategory) { + ResourceAttribute objectCategoryAttr = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_CATEGORY_NAME)); + assertNotNull("No objectCategory in " + shadow, objectCategoryAttr); + display("objectCategory of " + shadow + ": " + objectCategoryAttr); + assertEquals("Wrong objectCategory in " + shadow, expectedObjectCategory, objectCategoryAttr.getRealValue()); + } + + @Override + protected Entry assertLdapAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { + Entry entry = searchLdapAccount("(cn=" + cn + ")"); + assertAttribute(entry, "cn", cn); + assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); + return entry; + } + + protected Entry assertLdapSubAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { + Entry entry = searchLdapAccount(getSubLdapConnectionConfig(), "(cn=" + cn + ")"); + assertAttribute(entry, "cn", cn); + assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); + return entry; + } + + @Override + protected void assertNoLdapAccount(String uid) { + throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); + } + + protected void assertNoLdapAccount(String uid, String cn) throws LdapException, IOException, CursorException { + assertNoLdapAccount(null, uid, cn); + } + + protected void assertNoLdapSubAccount(String uid, String cn) throws LdapException, IOException, CursorException { + assertNoLdapAccount(getSubLdapConnectionConfig(), uid, cn); + } + + protected void assertNoLdapAccount(UserLdapConnectionConfig config, String uid, String cn) throws LdapException, IOException, CursorException { + LdapNetworkConnection connection = ldapConnect(config); + List entriesCn = ldapSearch(config, connection, "(cn=" + cn + ")"); + List entriesSamAccountName = ldapSearch(config, connection, "(sAMAccountName=" + uid + ")"); + ldapDisconnect(connection); + + assertEquals("Unexpected number of entries for cn=" + cn + ": " + entriesCn, 0, entriesCn.size()); + assertEquals("Unexpected number of entries for sAMAccountName=" + uid + ": " + entriesSamAccountName, 0, entriesSamAccountName.size()); + } + + @Override + protected String toAccountDn(String username) { + throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); + } + + @Override + protected String toAccountDn(String username, String fullName) { + return ("CN=" + fullName + "," + getPeopleLdapSuffix()); + } + + protected String toAccountSubDn(String username, String fullName) { + return ("CN=" + fullName + "," + getPeopleLdapSubSuffix()); + } + + @Override + protected Rdn toAccountRdn(String username, String fullName) { + try { + return new Rdn(new Ava("CN", fullName)); + } catch (LdapInvalidDnException e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + protected String toOrgDn(String cn) { + return "ou=" + cn + "," + getOrgsLdapSuffix(); + } + + protected String toOrgGroupDn(String groupCn, String orgName) { + return "cn=" + groupCn + "," + toOrgDn(orgName); + } + + protected Entry assertLdapOrg(String orgName) throws LdapException, IOException, CursorException { + String dn = toOrgDn(orgName); + Entry entry = getLdapEntry(dn); + assertNotNull("No entry " + dn, entry); + assertAttribute(entry, "ou", orgName); + return entry; + } + + protected Entry assertNoLdapOrg(String orgName) throws LdapException, IOException, CursorException { + String dn = toOrgDn(orgName); + Entry entry = getLdapEntry(dn); + assertNull("Unexpected org entry " + entry, entry); + return entry; + } + + protected Entry assertLdapOrgGroup(String groupCn, String orgName) throws LdapException, IOException, CursorException { + String dn = toOrgGroupDn(groupCn, orgName); + Entry entry = getLdapEntry(dn); + assertNotNull("No entry " + dn, entry); + assertAttribute(entry, "cn", groupCn); + return entry; + } + + protected Entry assertNoLdapOrgGroup(String groupCn, String orgName) throws LdapException, IOException, CursorException { + String dn = toOrgGroupDn(groupCn, orgName); + Entry entry = getLdapEntry(dn); + assertNull("Unexpected org group entry " + entry, entry); + return entry; + } + + protected void assertLdapPassword(String uid, String fullName, String password) throws LdapException, IOException, CursorException { + assertLdapPassword(null, uid, fullName, password); + } + + protected void assertLdapPassword(UserLdapConnectionConfig config, String uid, String fullName, String password) throws LdapException, IOException, CursorException { + Entry entry = getLdapAccountByCn(config, fullName); + assertLdapPassword(config, entry, password); + } + + protected void assertLdapPassword(String uid, String password) { + throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); + } + + protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws SchemaException { + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName), + prismContext); + return query; + } + + @Override + protected Entry createAccountEntry(String uid, String cn, String givenName, String sn) throws LdapException { + byte[] password = encodePassword("Secret.123"); + Entry entry = new DefaultEntry(toAccountDn(uid, cn), + "objectclass", getLdapAccountObjectClass(), + ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, uid, + "cn", cn, + "givenName", givenName, + "sn", sn, + ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512", + ATTRIBUTE_UNICODE_PWD_NAME, password); + return entry; + } + + private byte[] encodePassword(String password) { + String quotedPassword = "\"" + password + "\""; + try { + return quotedPassword.getBytes("UTF-16LE"); + } catch (UnsupportedEncodingException e) { + throw new SystemException(e.getMessage(), e); + } + } + + public void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { + assertAttribute(shadow, new QName(getResourceNamespace(), attrName), expectedValues); + } + + public void assertAttribute(PrismObject shadow, QName attrQname, T... expectedValues) { + List actualValues = ShadowUtil.getAttributeValues(shadow, attrQname); + PrismAsserts.assertSets("attribute " + attrQname + " in " + shadow, actualValues, expectedValues); + } + + protected abstract void assertAccountDisabled(PrismObject shadow); + + protected abstract void assertAccountEnabled(PrismObject shadow); + +} diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java index d99100da1ba..a3fde205e40 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java @@ -1,1257 +1,1256 @@ -/* - * Copyright (c) 2015-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.testing.conntest.ad; - -import static org.testng.AssertJUnit.*; - -import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; -import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_CREDENTIALS_PASSWORD_VALUE; - -import java.io.File; -import java.io.IOException; -import java.nio.charset.StandardCharsets; -import java.util.Collection; -import java.util.List; -import javax.xml.datatype.XMLGregorianCalendar; -import javax.xml.namespace.QName; - -import org.apache.commons.lang.StringUtils; -import org.apache.directory.api.ldap.model.cursor.CursorException; -import org.apache.directory.api.ldap.model.entry.*; -import org.apache.directory.api.ldap.model.exception.LdapException; -import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; -import org.apache.directory.api.ldap.model.name.Ava; -import org.apache.directory.api.ldap.model.name.Rdn; -import org.apache.directory.ldap.client.api.LdapNetworkConnection; -import org.testng.AssertJUnit; -import org.testng.annotations.Listeners; -import org.testng.annotations.Test; - -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismProperty; -import com.evolveum.midpoint.prism.delta.ObjectDelta; -import com.evolveum.midpoint.prism.delta.PropertyDelta; -import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.prism.query.ObjectPaging; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.prism.query.OrderDirection; -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.schema.SearchResultList; -import com.evolveum.midpoint.schema.SearchResultMetadata; -import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.schema.constants.SchemaConstants; -import com.evolveum.midpoint.schema.internals.InternalCounters; -import com.evolveum.midpoint.schema.processor.ResourceAttribute; -import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.schema.util.MiscSchemaUtil; -import com.evolveum.midpoint.schema.util.ObjectQueryUtil; -import com.evolveum.midpoint.schema.util.ShadowUtil; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.AbstractIntegrationTest; -import com.evolveum.midpoint.test.IntegrationTestTools; -import com.evolveum.midpoint.test.util.MidPointTestConstants; -import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.testing.conntest.AbstractLdapSynchronizationTest; -import com.evolveum.midpoint.util.MiscUtil; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -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; - -/** - * @author semancik - */ -@Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) -public abstract class AbstractAdLdapTest extends AbstractLdapSynchronizationTest - implements AdTestMixin { - - protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ad-ldap"); - - protected static final File ROLE_PIRATES_FILE = new File(TEST_DIR, "role-pirate.xml"); - protected static final String ROLE_PIRATES_OID = "5dd034e8-41d2-11e5-a123-001e8c717e5b"; - - protected static final File ROLE_META_ORG_FILE = new File(TEST_DIR, "role-meta-org.xml"); - protected static final String ROLE_META_ORG_OID = "f2ad0ace-45d7-11e5-af54-001e8c717e5b"; - - protected static final String ACCOUNT_JACK_SAM_ACCOUNT_NAME = "jack"; - protected static final String ACCOUNT_JACK_FULL_NAME = "Jack Sparrow"; - protected static final String ACCOUNT_JACK_PASSWORD = "qwe.123"; - - protected static final String USER_CPTBARBOSSA_FULL_NAME = "Captain Hector Barbossa"; - - private static final String GROUP_PIRATES_NAME = "pirates"; - private static final String GROUP_MELEE_ISLAND_NAME = "Mêlée Island"; - - protected static final int NUMBER_OF_ACCOUNTS = 12; - private static final String ASSOCIATION_GROUP_NAME = "group"; - - private static final String NS_EXTENSION = "http://whatever.com/my"; - private static final QName EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME = new QName(NS_EXTENSION, "showInAdvancedViewOnly"); - - private boolean allowDuplicateSearchResults = false; - - protected String jackAccountOid; - protected String groupPiratesOid; - protected String accountBarbossaOid; - protected String orgMeleeIslandOid; - protected String groupMeleeOid; - - @Override - public String getStartSystemCommand() { - return null; - } - - @Override - public String getStopSystemCommand() { - return null; - } - - @Override - protected File getBaseDir() { - return TEST_DIR; - } - - @Override - protected String getSyncTaskOid() { - return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b"; - } - - @Override - protected boolean useSsl() { - return true; - } - - @Override - protected String getLdapSuffix() { - return "DC=win,DC=evolveum,DC=com"; - } - - @Override - protected String getLdapBindDn() { - return "CN=midpoint admin1,CN=Users,DC=win,DC=evolveum,DC=com"; - } - - @Override - protected String getLdapBindPassword() { - return "mAZadlo911"; - } - - @Override - protected int getSearchSizeLimit() { - return -1; - } - - @Override - public String getPrimaryIdentifierAttributeName() { - return "objectGUID"; - } - - @Override - protected String getPeopleLdapSuffix() { - return "CN=Users," + getLdapSuffix(); - } - - @Override - protected String getGroupsLdapSuffix() { - return "CN=Users," + getLdapSuffix(); - } - - @Override - protected String getLdapAccountObjectClass() { - return "user"; - } - - @Override - protected String getLdapGroupObjectClass() { - return "group"; - } - - @Override - protected String getLdapGroupMemberAttribute() { - return "member"; - } - - private QName getAssociationGroupQName() { - return new QName(MidPointConstants.NS_RI, ASSOCIATION_GROUP_NAME); - } - - @Override - protected boolean allowDuplicateSearchResults() { - return allowDuplicateSearchResults; - } - - @Override - protected File getSyncTaskInetOrgPersonFile() { - return new File(getBaseDir(), "task-sync-user.xml"); - } - - @Override - protected boolean isGroupMemberMandatory() { - return false; - } - - protected String getLdapConnectorClassName() { - return AdTestMixin.AD_CONNECTOR_TYPE; - } - - @Override - public void initSystem(Task initTask, OperationResult initResult) throws Exception { - super.initSystem(initTask, initResult); - - binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_OBJECT_GUID_NAME); - binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_UNICODE_PWD_NAME); - - // Users - repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); - repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); - - // Roles - repoAddObjectFromFile(ROLE_PIRATES_FILE, initResult); - repoAddObjectFromFile(ROLE_META_ORG_FILE, initResult); - - } - - @Test - @Override - public void test000Sanity() throws Exception { - super.test000Sanity(); - - assertLdapPasswordByFullName(ACCOUNT_JACK_FULL_NAME, ACCOUNT_JACK_PASSWORD); - cleanupDelete(toAccountDn(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME)); - cleanupDelete(toAccountDn(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME)); - cleanupDelete(toAccountDn(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME)); - cleanupDelete(toGroupDn(GROUP_MELEE_ISLAND_NAME)); - cleanupDelete(toGroupDn(GROUP_FOOLS_CN)); - } - - @Test - @Override - public void test020Schema() throws Exception { - accountObjectClassDefinition = assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); - - assertLdapConnectorInstances(1); - } - - // test050 in subclasses - - @Test - public void test100SeachJackBySamAccountName() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = createSamAccountNameQuery(ACCOUNT_JACK_SAM_ACCOUNT_NAME); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - when(); - SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - - // THEN - result.computeStatus(); - TestUtil.assertSuccess(result); - - assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); - - PrismObject shadow = shadows.get(0); - display("Shadow", shadow); - assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); - jackAccountOid = shadow.getOid(); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = shadows.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(1); - } - - @Test - public void test105SeachPiratesByCn() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); - ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_PIRATES_NAME), prismContext); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - when(); - SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); - - // THEN - result.computeStatus(); - TestUtil.assertSuccess(result); - - assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); - - PrismObject shadow = shadows.get(0); - display("Shadow", shadow); - groupPiratesOid = shadow.getOid(); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = shadows.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(1); - } - - @Test - public void test110GetJack() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - when(); - PrismObject shadow = modelService.getObject(ShadowType.class, jackAccountOid, null, task, result); - - // THEN - result.computeStatus(); - TestUtil.assertSuccess(result); - display("Shadow", shadow); - assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); - jackAccountOid = shadow.getOid(); - - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - - assertAttribute(shadow, "dn", "CN=Jack Sparrow,CN=Users,DC=win,DC=evolveum,DC=com"); - assertAttribute(shadow, "cn", ACCOUNT_JACK_FULL_NAME); - assertAttribute(shadow, "sn", "Sparrow"); - assertAttribute(shadow, "info", "The best pirate the world has ever seen"); - assertAttribute(shadow, "sAMAccountName", ACCOUNT_JACK_SAM_ACCOUNT_NAME); - assertAttribute(shadow, "lastLogon", 0L); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - assertLdapConnectorInstances(1); - } - - /** - * No paging. It should return all accounts. - */ - @Test - public void test150SeachAllAccounts() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); - rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); - - // WHEN - SearchResultList> searchResultList = doSearch(query, - NUMBER_OF_ACCOUNTS, task, result); - - // TODO: why 11? should be 1 - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 9); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * Blocksize is 5, so this is in one block. - */ - @Test - public void test152SeachFirst2Accounts() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(); - paging.setMaxSize(2); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 2, task, result); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * Blocksize is 5, so this gets more than two blocks. - */ - @Test - public void test154SeachFirst11Accounts() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(); - paging.setMaxSize(11); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 11, task, result); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - @Test - public void test162SeachFirst2AccountsOffset0() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(); - paging.setOffset(0); - paging.setMaxSize(2); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 2, task, result); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * Blocksize is 5, so this is in one block. - * There is offset, so VLV should be used. - * No explicit sorting. - */ - @Test - public void test172Search2AccountsOffset1() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); - query.setPaging(paging); - - SearchResultList> searchResultList = doSearch(query, 2, task, result); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * Blocksize is 5, so this gets more than two blocks. - * There is offset, so VLV should be used. - * No explicit sorting. - */ - @Test - public void test174SeachFirst11AccountsOffset2() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(2, 11); - query.setPaging(paging); - - allowDuplicateSearchResults = true; - - // WHEN - SearchResultList> searchResultList = doSearch(query, 11, task, result); - - // THEN - allowDuplicateSearchResults = false; - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = searchResultList.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - /** - * Blocksize is 5, so this is in one block. - * There is offset, so VLV should be used. - * Explicit sorting. - */ - @Test - public void test182Search2AccountsOffset1SortCn() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - - ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); - paging.setOrdering(getAttributePath(resource, "cn"), OrderDirection.ASCENDING); - query.setPaging(paging); - - SearchResultList> shadows = doSearch(query, 2, task, result); - - assertAccountShadow(shadows.get(0), "CN=Administrator,CN=Users,DC=win,DC=evolveum,DC=com"); - assertAccountShadow(shadows.get(1), "CN=Chuck LeChuck,CN=Users,DC=win,DC=evolveum,DC=com"); - - assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); - assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); - - SearchResultMetadata metadata = shadows.getMetadata(); - if (metadata != null) { - assertFalse(metadata.isPartialResults()); - } - - assertLdapConnectorInstances(2); - } - - @Test - public void test200AssignAccountBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - long tsStart = System.currentTimeMillis(); - - // WHEN - when(); - assignAccountToUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - - // THEN - then(); - assertSuccess(result); - - long tsEnd = System.currentTimeMillis(); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "title", null); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getShadowModel(shadowOid); - display("Shadow (model)", shadow); - accountBarbossaOid = shadow.getOid(); - Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); - String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); - assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); - - assertEquals("Wrong ICFS UID", - formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), - accountBarbossaIcfUid); - - assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); - - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); - assertNotNull("No createTimestamp in " + shadow, createTimestampAttribute); - XMLGregorianCalendar createTimestamp = createTimestampAttribute.getRealValue(); - // LDAP server may be on a different host. Allow for some clock offset. - TestUtil.assertBetween("Wrong createTimestamp in " + shadow, roundTsDown(tsStart) - 120000, roundTsUp(tsEnd) + 120000, XmlTypeConverter.toMillis(createTimestamp)); - - assertLdapConnectorInstances(2); - } - - @Test - public void test210ModifyAccountBarbossaTitle() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta delta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, "title"); - ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); - PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( - ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); - delta.addModification(attrDelta); - - // WHEN - when(); - modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "title", "Captain"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapConnectorInstances(2); - } - - @Test - public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta delta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); - ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); - PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( - ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); - delta.addModification(attrDelta); - - // WHEN - when(); - modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "showInAdvancedViewOnly", "TRUE"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapConnectorInstances(2); - } - - /** - * Modify USER, test boolean value mapping. - */ - @Test - public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta delta = prismContext.deltaFactory().object() - .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); - QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); - ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); - PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( - ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); - delta.addModification(attrDelta); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, ItemPath.create(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), - task, result, Boolean.FALSE); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "showInAdvancedViewOnly", "FALSE"); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapConnectorInstances(2); - } - - @Test - public void test220ModifyUserBarbossaPassword() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ProtectedStringType userPasswordPs = new ProtectedStringType(); - userPasswordPs.setClearValue(USER_BARBOSSA_PASSWORD_2); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "title", "Captain"); - assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_2); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapConnectorInstances(2); - } - - /** - * MID-5242 - */ - @Test - public void test222ModifyUserBarbossaPasswordNational() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ProtectedStringType userPasswordPs = new ProtectedStringType(); - userPasswordPs.setClearValue(USER_BARBOSSA_PASSWORD_AD_1); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, "title", "Captain"); - assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - assertLdapConnectorInstances(2); - } - - @Test - public void test230DisableUserBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // precondition - assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.DISABLED); - - // THEN - then(); - assertSuccess(result); - - assertLdapConnectorInstances(2); - - PrismObject user = getUser(USER_BARBOSSA_OID); - assertAdministrativeStatus(user, ActivationStatusType.DISABLED); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountDisabled(shadow); - - try { - assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); - AssertJUnit.fail("Password authentication works, but it should fail"); - } catch (SecurityException e) { - // this is expected - } - - assertLdapConnectorInstances(2); - } - - @Test - public void test239EnableUserBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_BARBOSSA_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.ENABLED); - - // THEN - then(); - assertSuccess(result); - - PrismObject user = getUser(USER_BARBOSSA_OID); - assertAdministrativeStatus(user, ActivationStatusType.ENABLED); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountEnabled(shadow); - - assertLdapConnectorInstances(2); - } - - /** - * This should create account with a group. And disabled. - */ - @Test - public void test250AssignGuybrushPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - modifyUserReplace(USER_GUYBRUSH_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.DISABLED); - - // WHEN - when(); - assignRole(USER_GUYBRUSH_OID, ROLE_PIRATES_OID, task, result); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - display("Entry", entry); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - - assertLdapGroupMember(entry, GROUP_PIRATES_NAME); - - PrismObject user = getUser(USER_GUYBRUSH_OID); - assertAdministrativeStatus(user, ActivationStatusType.DISABLED); - String shadowOid = getSingleLinkOid(user); - - PrismObject shadow = getObject(ShadowType.class, shadowOid); - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - assertAccountDisabled(shadow); - - assertLdapConnectorInstances(2); - } - - @Test - public void test255ModifyUserGuybrushPassword() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ProtectedStringType userPasswordPs = new ProtectedStringType(); - userPasswordPs.setClearValue("wanna.be.a.123"); - - // WHEN - when(); - modifyUserReplace(USER_GUYBRUSH_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); - - try { - assertLdapPasswordByFullName(USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); - AssertJUnit.fail("Password authentication works, but it should fail"); - } catch (SecurityException e) { - // this is expected, account is disabled - } - - assertLdapConnectorInstances(2); - } - - @Test - public void test260EnableGyubrush() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - modifyUserReplace(USER_GUYBRUSH_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.ENABLED); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - PrismObject user = getUser(USER_GUYBRUSH_OID); - assertAdministrativeStatus(user, ActivationStatusType.ENABLED); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); - - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - assertAccountEnabled(shadow); - - assertLdapPasswordByFullName(USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); - - assertLdapConnectorInstances(2); - } - - @Test - public void test300AssignBarbossaPirates() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - assignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - display("Entry", entry); - assertAttribute(entry, "title", "Captain"); - - assertLdapGroupMember(entry, GROUP_PIRATES_NAME); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - PrismObject shadow = getObject(ShadowType.class, shadowOid); - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - - assertLdapConnectorInstances(2); - } - - @Test - public void test390ModifyUserBarbossaRename() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_BARBOSSA_OID, UserType.F_NAME, - PrismTestUtil.createPolyString(USER_CPTBARBOSSA_USERNAME)); - objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, - PrismTestUtil.createPolyString(USER_CPTBARBOSSA_FULL_NAME)); - Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); - - // WHEN - when(); - modelService.executeChanges(deltas, null, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); - assertAttribute(entry, "title", "Captain"); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - PrismObject shadow = getObject(ShadowType.class, shadowOid); - display("Shadow after rename (model)", shadow); - - PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); - display("Shadow after rename (repo)", repoShadow); - - assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - - assertLdapConnectorInstances(2); - } - - // TODO: create account with a group membership - - @Test - public void test395UnAssignBarbossaPirates() throws Exception { - // TODO: do this on another account. There is a bad interference with rename. - - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - unassignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); - display("Entry", entry); - assertAttribute(entry, "title", "Captain"); - - assertLdapNoGroupMember(entry, GROUP_PIRATES_NAME); - - PrismObject user = getUser(USER_BARBOSSA_OID); - String shadowOid = getSingleLinkOid(user); - assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); - - PrismObject shadow = getObject(ShadowType.class, shadowOid); - IntegrationTestTools.assertNoAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); - - assertLdapConnectorInstances(2); - } - - @Test - public void test399UnAssignAccountBarbossa() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - unassignAccountFromUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); - assertNoLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); - - PrismObject user = getUser(USER_BARBOSSA_OID); - assertNoLinkedAccount(user); - - assertLdapConnectorInstances(2); - } - - @Test - public void test500AddOrgMeleeIsland() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - PrismObject org = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(OrgType.class).instantiate(); - OrgType orgType = org.asObjectable(); - orgType.setName(new PolyStringType(GROUP_MELEE_ISLAND_NAME)); - AssignmentType metaroleAssignment = new AssignmentType(); - ObjectReferenceType metaroleRef = new ObjectReferenceType(); - metaroleRef.setOid(ROLE_META_ORG_OID); - metaroleRef.setType(RoleType.COMPLEX_TYPE); - metaroleAssignment.setTargetRef(metaroleRef); - orgType.getAssignment().add(metaroleAssignment); - - // WHEN - when(); - addObject(org, task, result); - - // THEN - then(); - result.computeStatus(); - TestUtil.assertSuccess(result); - - orgMeleeIslandOid = org.getOid(); - assertLdapGroup(GROUP_MELEE_ISLAND_NAME); - - org = getObject(OrgType.class, orgMeleeIslandOid); - groupMeleeOid = getSingleLinkOid(org); - PrismObject shadow = getShadowModel(groupMeleeOid); - display("Shadow (model)", shadow); - - assertLdapConnectorInstances(2); - } - - @Test - public void test510AssignGuybrushMeleeIsland() throws Exception { - // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); - - // WHEN - when(); - assignOrg(USER_GUYBRUSH_OID, orgMeleeIslandOid, task, result); - - // THEN - then(); - assertSuccess(result); - - Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); - - PrismObject user = getUser(USER_GUYBRUSH_OID); - String shadowOid = getSingleLinkOid(user); - PrismObject shadow = getShadowModel(shadowOid); - display("Shadow (model)", shadow); - - assertLdapGroupMember(entry, GROUP_MELEE_ISLAND_NAME); - - IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupMeleeOid); - - assertLdapConnectorInstances(2); - } - - @Override - protected void doAdditionalRenameModifications(LdapNetworkConnection connection) throws LdapException { - Modification mod = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, - ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, ACCOUNT_HTM_UID); - connection.modify(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN), mod); - display("Modified " + toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN) + " " + ATTRIBUTE_SAM_ACCOUNT_NAME_NAME + - " -> " + ACCOUNT_HTM_UID + ": " + mod); - } - - @Override - protected String getAccountHtmCnAfterRename() { - return ACCOUNT_HTM_CN; - } - - @Override - protected void assertAccountShadow(PrismObject shadow, String dn) throws SchemaException { - super.assertAccountShadow(shadow, dn); - ResourceAttribute primaryIdAttr = ShadowUtil.getAttribute(shadow, getPrimaryIdentifierAttributeQName()); - assertNotNull("No primary identifier (" + getPrimaryIdentifierAttributeQName() + " in " + shadow, primaryIdAttr); - String primaryId = primaryIdAttr.getRealValue(); - assertTrue("Unexpected chars in primary ID: '" + primaryId + "'", primaryId.matches("[a-z0-9\\-]+")); - } - - @Override - protected Entry assertLdapAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { - Entry entry = searchLdapAccount("(cn=" + cn + ")"); - assertAttribute(entry, "cn", cn); - assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); - return entry; - } - - @Override - protected void assertNoLdapAccount(String uid) { - throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); - } - - protected void assertNoLdapAccount(String uid, String cn) throws LdapException, IOException, CursorException { - LdapNetworkConnection connection = ldapConnect(); - List entriesCn = ldapSearch(connection, "(cn=" + cn + ")"); - List entriesSamAccountName = ldapSearch(connection, "(sAMAccountName=" + uid + ")"); - ldapDisconnect(connection); - - assertEquals("Unexpected number of entries for cn=" + cn + ": " + entriesCn, 0, entriesCn.size()); - assertEquals("Unexpected number of entries for sAMAccountName=" + uid + ": " + entriesSamAccountName, 0, entriesSamAccountName.size()); - } - - @Override - protected String toAccountDn(String username) { - throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); - } - - @Override - protected String toAccountDn(String username, String fullName) { - return "CN=" + fullName + "," + getPeopleLdapSuffix(); - } - - @Override - protected Rdn toAccountRdn(String username, String fullName) { - try { - return new Rdn(new Ava("CN", fullName)); - } catch (LdapInvalidDnException e) { - throw new IllegalStateException(e.getMessage(), e); - } - } - - protected void assertLdapPasswordByFullName(String fullName, String password) - throws LdapException, IOException, CursorException { - Entry entry = getLdapAccountByCn(fullName); - assertLdapPassword(entry, password); - } - - protected void assertLdapPassword(String uid, String password) { - throw new UnsupportedOperationException( - "Boom! Cannot do this here. This is bloody AD! We need full name!"); - } - - protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws SchemaException { - ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); - ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName), - prismContext); - return query; - } - - @Override - protected Entry createAccountEntry(String uid, String cn, String givenName, String sn) throws LdapException { - byte[] password = encodePassword("Secret.123"); - Entry entry = new DefaultEntry(toAccountDn(uid, cn), - "objectclass", getLdapAccountObjectClass(), - ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, uid, - "cn", cn, - "givenName", givenName, - "sn", sn, - ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512", - ATTRIBUTE_UNICODE_PWD_NAME, password); - return entry; - } - - private byte[] encodePassword(String password) { - String quotedPassword = "\"" + password + "\""; - return quotedPassword.getBytes(StandardCharsets.UTF_16LE); - } - - @Override - protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) - throws ObjectNotFoundException, SchemaException { - OperationResult result = createOperationResult("assertStepSyncToken"); - Task task = taskManager.getTask(syncTaskOid, result); - PrismProperty syncTokenProperty = task.getExtensionPropertyOrClone(SchemaConstants.SYNC_TOKEN); - assertNotNull("No sync token", syncTokenProperty); - assertNotNull("No sync token value", syncTokenProperty.getRealValue()); - assertNotNull("Empty sync token value", StringUtils.isBlank(syncTokenProperty.getRealValue())); - result.computeStatus(); - TestUtil.assertSuccess(result); - } - - public void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { - assertAttribute(shadow, new QName(getResourceNamespace(), attrName), expectedValues); - } - - public void assertAttribute(PrismObject shadow, QName attrQname, T... expectedValues) { - List actualValues = ShadowUtil.getAttributeValues(shadow, attrQname); - PrismAsserts.assertSets("attribute " + attrQname + " in " + shadow, actualValues, expectedValues); - } - - protected abstract void assertAccountDisabled(PrismObject shadow); - - protected abstract void assertAccountEnabled(PrismObject shadow); -} +/* + * Copyright (c) 2015-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.testing.conntest.ad; + +import static org.testng.AssertJUnit.*; + +import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_ACTIVATION_ADMINISTRATIVE_STATUS; +import static com.evolveum.midpoint.schema.constants.SchemaConstants.PATH_CREDENTIALS_PASSWORD_VALUE; + +import java.io.File; +import java.io.IOException; +import java.nio.charset.StandardCharsets; +import java.util.Collection; +import java.util.List; +import javax.xml.datatype.XMLGregorianCalendar; +import javax.xml.namespace.QName; + +import org.apache.commons.lang.StringUtils; +import org.apache.directory.api.ldap.model.cursor.CursorException; +import org.apache.directory.api.ldap.model.entry.*; +import org.apache.directory.api.ldap.model.exception.LdapException; +import org.apache.directory.api.ldap.model.exception.LdapInvalidDnException; +import org.apache.directory.api.ldap.model.name.Ava; +import org.apache.directory.api.ldap.model.name.Rdn; +import org.apache.directory.ldap.client.api.LdapNetworkConnection; +import org.testng.AssertJUnit; +import org.testng.annotations.Listeners; +import org.testng.annotations.Test; + +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismProperty; +import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.path.ItemPath; +import com.evolveum.midpoint.prism.query.ObjectPaging; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.prism.query.OrderDirection; +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.schema.SearchResultList; +import com.evolveum.midpoint.schema.SearchResultMetadata; +import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.schema.constants.SchemaConstants; +import com.evolveum.midpoint.schema.internals.InternalCounters; +import com.evolveum.midpoint.schema.processor.ResourceAttribute; +import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.schema.util.MiscSchemaUtil; +import com.evolveum.midpoint.schema.util.ObjectQueryUtil; +import com.evolveum.midpoint.schema.util.ShadowUtil; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.AbstractIntegrationTest; +import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.util.MidPointTestConstants; +import com.evolveum.midpoint.test.util.TestUtil; +import com.evolveum.midpoint.testing.conntest.AbstractLdapSynchronizationTest; +import com.evolveum.midpoint.util.MiscUtil; +import com.evolveum.midpoint.util.exception.ObjectNotFoundException; +import com.evolveum.midpoint.util.exception.SchemaException; +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; + +/** + * @author semancik + */ +@Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) +public abstract class AbstractAdLdapTest extends AbstractLdapSynchronizationTest + implements AdTestMixin { + + protected static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "ad-ldap"); + + protected static final File ROLE_PIRATES_FILE = new File(TEST_DIR, "role-pirate.xml"); + protected static final String ROLE_PIRATES_OID = "5dd034e8-41d2-11e5-a123-001e8c717e5b"; + + protected static final File ROLE_META_ORG_FILE = new File(TEST_DIR, "role-meta-org.xml"); + protected static final String ROLE_META_ORG_OID = "f2ad0ace-45d7-11e5-af54-001e8c717e5b"; + + protected static final String ACCOUNT_JACK_SAM_ACCOUNT_NAME = "jack"; + protected static final String ACCOUNT_JACK_FULL_NAME = "Jack Sparrow"; + protected static final String ACCOUNT_JACK_PASSWORD = "qwe.123"; + + protected static final String USER_CPTBARBOSSA_FULL_NAME = "Captain Hector Barbossa"; + + private static final String GROUP_PIRATES_NAME = "pirates"; + private static final String GROUP_MELEE_ISLAND_NAME = "Mêlée Island"; + + protected static final int NUMBER_OF_ACCOUNTS = 12; + private static final String ASSOCIATION_GROUP_NAME = "group"; + + private static final String NS_EXTENSION = "http://whatever.com/my"; + private static final QName EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME = new QName(NS_EXTENSION, "showInAdvancedViewOnly"); + + private boolean allowDuplicateSearchResults = false; + + protected String jackAccountOid; + protected String groupPiratesOid; + protected String accountBarbossaOid; + protected String orgMeleeIslandOid; + protected String groupMeleeOid; + + @Override + public String getStartSystemCommand() { + return null; + } + + @Override + public String getStopSystemCommand() { + return null; + } + + @Override + protected File getBaseDir() { + return TEST_DIR; + } + + @Override + protected String getSyncTaskOid() { + return "cd1e0ff2-0099-11e5-9e22-001e8c717e5b"; + } + + @Override + protected boolean useSsl() { + return true; + } + + @Override + protected String getLdapSuffix() { + return "DC=win,DC=evolveum,DC=com"; + } + + @Override + protected String getLdapBindDn() { + return "CN=midpoint admin1,CN=Users,DC=win,DC=evolveum,DC=com"; + } + + @Override + protected String getLdapBindPassword() { + return "mAZadlo911"; + } + + @Override + protected int getSearchSizeLimit() { + return -1; + } + + @Override + public String getPrimaryIdentifierAttributeName() { + return "objectGUID"; + } + + @Override + protected String getPeopleLdapSuffix() { + return "CN=Users," + getLdapSuffix(); + } + + @Override + protected String getGroupsLdapSuffix() { + return "CN=Users," + getLdapSuffix(); + } + + @Override + protected String getLdapAccountObjectClass() { + return "user"; + } + + @Override + protected String getLdapGroupObjectClass() { + return "group"; + } + + @Override + protected String getLdapGroupMemberAttribute() { + return "member"; + } + + private QName getAssociationGroupQName() { + return new QName(MidPointConstants.NS_RI, ASSOCIATION_GROUP_NAME); + } + + @Override + protected boolean allowDuplicateSearchResults() { + return allowDuplicateSearchResults; + } + + @Override + protected File getSyncTaskInetOrgPersonFile() { + return new File(getBaseDir(), "task-sync-user.xml"); + } + + @Override + protected boolean isGroupMemberMandatory() { + return false; + } + + protected String getLdapConnectorClassName() { + return AdTestMixin.AD_CONNECTOR_TYPE; + } + + @Override + public void initSystem(Task initTask, OperationResult initResult) throws Exception { + super.initSystem(initTask, initResult); + + binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_OBJECT_GUID_NAME); + binaryAttributeDetector.addBinaryAttribute(ATTRIBUTE_UNICODE_PWD_NAME); + + // Users + repoAddObjectFromFile(USER_BARBOSSA_FILE, initResult); + repoAddObjectFromFile(USER_GUYBRUSH_FILE, initResult); + + // Roles + repoAddObjectFromFile(ROLE_PIRATES_FILE, initResult); + repoAddObjectFromFile(ROLE_META_ORG_FILE, initResult); + + } + + @Test + @Override + public void test000Sanity() throws Exception { + super.test000Sanity(); + + assertLdapPasswordByFullName(ACCOUNT_JACK_FULL_NAME, ACCOUNT_JACK_PASSWORD); + cleanupDelete(toAccountDn(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME)); + cleanupDelete(toAccountDn(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME)); + cleanupDelete(toAccountDn(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME)); + cleanupDelete(toGroupDn(GROUP_MELEE_ISLAND_NAME)); + cleanupDelete(toGroupDn(GROUP_FOOLS_CN)); + } + + @Test + @Override + public void test020Schema() throws Exception { + accountObjectClassDefinition = assertAdResourceSchema(resource, getAccountObjectClass(), prismContext); + + assertLdapConnectorInstances(1); + } + + // test050 in subclasses + + @Test + public void test100SeachJackBySamAccountName() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = createSamAccountNameQuery(ACCOUNT_JACK_SAM_ACCOUNT_NAME); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + when(); + SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); + + // THEN + result.computeStatus(); + TestUtil.assertSuccess(result); + + assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); + + PrismObject shadow = shadows.get(0); + display("Shadow", shadow); + assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); + jackAccountOid = shadow.getOid(); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 2); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = shadows.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(1); + } + + @Test + public void test105SeachPiratesByCn() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getGroupObjectClass(), prismContext); + ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter("cn", GROUP_PIRATES_NAME), prismContext); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + when(); + SearchResultList> shadows = modelService.searchObjects(ShadowType.class, query, null, task, result); + + // THEN + result.computeStatus(); + TestUtil.assertSuccess(result); + + assertEquals("Unexpected search result: " + shadows, 1, shadows.size()); + + PrismObject shadow = shadows.get(0); + display("Shadow", shadow); + groupPiratesOid = shadow.getOid(); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = shadows.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(1); + } + + @Test + public void test110GetJack() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + when(); + PrismObject shadow = modelService.getObject(ShadowType.class, jackAccountOid, null, task, result); + + // THEN + result.computeStatus(); + TestUtil.assertSuccess(result); + display("Shadow", shadow); + assertAccountShadow(shadow, toAccountDn(ACCOUNT_JACK_SAM_ACCOUNT_NAME, ACCOUNT_JACK_FULL_NAME)); + jackAccountOid = shadow.getOid(); + + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + + assertAttribute(shadow, "dn", "CN=Jack Sparrow,CN=Users,DC=win,DC=evolveum,DC=com"); + assertAttribute(shadow, "cn", ACCOUNT_JACK_FULL_NAME); + assertAttribute(shadow, "sn", "Sparrow"); + assertAttribute(shadow, "info", "The best pirate the world has ever seen"); + assertAttribute(shadow, "sAMAccountName", ACCOUNT_JACK_SAM_ACCOUNT_NAME); + assertAttribute(shadow, "lastLogon", 0L); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + assertLdapConnectorInstances(1); + } + + /** + * No paging. It should return all accounts. + */ + @Test + public void test150SeachAllAccounts() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + rememberCounter(InternalCounters.CONNECTOR_OPERATION_COUNT); + rememberCounter(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT); + + // WHEN + SearchResultList> searchResultList = doSearch(query, + NUMBER_OF_ACCOUNTS, task, result); + + // TODO: why 11? should be 1 + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 9); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * Blocksize is 5, so this is in one block. + */ + @Test + public void test152SeachFirst2Accounts() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(); + paging.setMaxSize(2); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 2, task, result); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * Blocksize is 5, so this gets more than two blocks. + */ + @Test + public void test154SeachFirst11Accounts() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(); + paging.setMaxSize(11); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 11, task, result); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + @Test + public void test162SeachFirst2AccountsOffset0() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(); + paging.setOffset(0); + paging.setMaxSize(2); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 2, task, result); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * Blocksize is 5, so this is in one block. + * There is offset, so VLV should be used. + * No explicit sorting. + */ + @Test + public void test172Search2AccountsOffset1() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); + query.setPaging(paging); + + SearchResultList> searchResultList = doSearch(query, 2, task, result); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * Blocksize is 5, so this gets more than two blocks. + * There is offset, so VLV should be used. + * No explicit sorting. + */ + @Test + public void test174SeachFirst11AccountsOffset2() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(2, 11); + query.setPaging(paging); + + allowDuplicateSearchResults = true; + + // WHEN + SearchResultList> searchResultList = doSearch(query, 11, task, result); + + // THEN + allowDuplicateSearchResults = false; + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = searchResultList.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + /** + * Blocksize is 5, so this is in one block. + * There is offset, so VLV should be used. + * Explicit sorting. + */ + @Test + public void test182Search2AccountsOffset1SortCn() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + + ObjectPaging paging = prismContext.queryFactory().createPaging(1, 2); + paging.setOrdering(getAttributePath(resource, "cn"), OrderDirection.ASCENDING); + query.setPaging(paging); + + SearchResultList> shadows = doSearch(query, 2, task, result); + + assertAccountShadow(shadows.get(0), "CN=Administrator,CN=Users,DC=win,DC=evolveum,DC=com"); + assertAccountShadow(shadows.get(1), "CN=Chuck LeChuck,CN=Users,DC=win,DC=evolveum,DC=com"); + + assertCounterIncrement(InternalCounters.CONNECTOR_OPERATION_COUNT, 1); + assertCounterIncrement(InternalCounters.CONNECTOR_SIMULATED_PAGING_SEARCH_COUNT, 0); + + SearchResultMetadata metadata = shadows.getMetadata(); + if (metadata != null) { + assertFalse(metadata.isPartialResults()); + } + + assertLdapConnectorInstances(2); + } + + @Test + public void test200AssignAccountBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + long tsStart = System.currentTimeMillis(); + + // WHEN + when(); + assignAccountToUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); + + // THEN + then(); + assertSuccess(result); + + long tsEnd = System.currentTimeMillis(); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "title", null); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getShadowModel(shadowOid); + display("Shadow (model)", shadow); + accountBarbossaOid = shadow.getOid(); + Collection> identifiers = ShadowUtil.getPrimaryIdentifiers(shadow); + String accountBarbossaIcfUid = (String) identifiers.iterator().next().getRealValue(); + assertNotNull("No identifier in " + shadow, accountBarbossaIcfUid); + + assertEquals("Wrong ICFS UID", + formatGuidToDashedNotation(MiscUtil.binaryToHex(entry.get(getPrimaryIdentifierAttributeName()).getBytes())), + accountBarbossaIcfUid); + + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + ResourceAttribute createTimestampAttribute = ShadowUtil.getAttribute(shadow, new QName(MidPointConstants.NS_RI, "createTimeStamp")); + assertNotNull("No createTimestamp in " + shadow, createTimestampAttribute); + XMLGregorianCalendar createTimestamp = createTimestampAttribute.getRealValue(); + // LDAP server may be on a different host. Allow for some clock offset. + TestUtil.assertBetween("Wrong createTimestamp in " + shadow, roundTsDown(tsStart) - 120000, roundTsUp(tsEnd) + 120000, XmlTypeConverter.toMillis(createTimestamp)); + + assertLdapConnectorInstances(2); + } + + @Test + public void test210ModifyAccountBarbossaTitle() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, "title"); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, "Captain"); + delta.addModification(attrDelta); + + // WHEN + when(); + modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "title", "Captain"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapConnectorInstances(2); + } + + @Test + public void test212ModifyAccountBarbossaShowInAdvancedViewOnlyTrue() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); + delta.addModification(attrDelta); + + // WHEN + when(); + modelService.executeChanges(MiscSchemaUtil.createCollection(delta), null, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "showInAdvancedViewOnly", "TRUE"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapConnectorInstances(2); + } + + /** + * Modify USER, test boolean value mapping. + */ + @Test + public void test213ModifyUserBarbossaShowInAdvancedViewOnlyFalse() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, "showInAdvancedViewOnly"); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, Boolean.TRUE); + delta.addModification(attrDelta); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, ItemPath.create(UserType.F_EXTENSION, EXTENSION_SHOW_IN_ADVANCED_VIEW_ONLY_QNAME), + task, result, Boolean.FALSE); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "showInAdvancedViewOnly", "FALSE"); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapConnectorInstances(2); + } + + @Test + public void test220ModifyUserBarbossaPassword() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ProtectedStringType userPasswordPs = new ProtectedStringType(); + userPasswordPs.setClearValue(USER_BARBOSSA_PASSWORD_2); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "title", "Captain"); + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_2); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapConnectorInstances(2); + } + + /** + * MID-5242 + */ + @Test + public void test222ModifyUserBarbossaPasswordNational() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ProtectedStringType userPasswordPs = new ProtectedStringType(); + userPasswordPs.setClearValue(USER_BARBOSSA_PASSWORD_AD_1); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, "title", "Captain"); + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertLdapConnectorInstances(2); + } + + @Test + public void test230DisableUserBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // precondition + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.DISABLED); + + // THEN + then(); + assertSuccess(result); + + assertLdapConnectorInstances(2); + + PrismObject user = getUser(USER_BARBOSSA_OID); + assertAdministrativeStatus(user, ActivationStatusType.DISABLED); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountDisabled(shadow); + + try { + assertLdapPasswordByFullName(USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD_AD_1); + AssertJUnit.fail("Password authentication works, but it should fail"); + } catch (SecurityException e) { + // this is expected + } + + assertLdapConnectorInstances(2); + } + + @Test + public void test239EnableUserBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_BARBOSSA_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.ENABLED); + + // THEN + then(); + assertSuccess(result); + + PrismObject user = getUser(USER_BARBOSSA_OID); + assertAdministrativeStatus(user, ActivationStatusType.ENABLED); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountEnabled(shadow); + + assertLdapConnectorInstances(2); + } + + /** + * This should create account with a group. And disabled. + */ + @Test + public void test250AssignGuybrushPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + modifyUserReplace(USER_GUYBRUSH_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.DISABLED); + + // WHEN + when(); + assignRole(USER_GUYBRUSH_OID, ROLE_PIRATES_OID, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + display("Entry", entry); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + + assertLdapGroupMember(entry, GROUP_PIRATES_NAME); + + PrismObject user = getUser(USER_GUYBRUSH_OID); + assertAdministrativeStatus(user, ActivationStatusType.DISABLED); + String shadowOid = getSingleLinkOid(user); + + PrismObject shadow = getObject(ShadowType.class, shadowOid); + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + assertAccountDisabled(shadow); + + assertLdapConnectorInstances(2); + } + + @Test + public void test255ModifyUserGuybrushPassword() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ProtectedStringType userPasswordPs = new ProtectedStringType(); + userPasswordPs.setClearValue("wanna.be.a.123"); + + // WHEN + when(); + modifyUserReplace(USER_GUYBRUSH_OID, PATH_CREDENTIALS_PASSWORD_VALUE, task, result, userPasswordPs); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "514"); + + try { + assertLdapPasswordByFullName(USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); + AssertJUnit.fail("Password authentication works, but it should fail"); + } catch (SecurityException e) { + // this is expected, account is disabled + } + + assertLdapConnectorInstances(2); + } + + @Test + public void test260EnableGyubrush() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + modifyUserReplace(USER_GUYBRUSH_OID, PATH_ACTIVATION_ADMINISTRATIVE_STATUS, task, result, ActivationStatusType.ENABLED); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + PrismObject user = getUser(USER_GUYBRUSH_OID); + assertAdministrativeStatus(user, ActivationStatusType.ENABLED); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + assertAccountEnabled(shadow); + + assertLdapPasswordByFullName(USER_GUYBRUSH_FULL_NAME, "wanna.be.a.123"); + + assertLdapConnectorInstances(2); + } + + @Test + public void test300AssignBarbossaPirates() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + assignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + display("Entry", entry); + assertAttribute(entry, "title", "Captain"); + + assertLdapGroupMember(entry, GROUP_PIRATES_NAME); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + PrismObject shadow = getObject(ShadowType.class, shadowOid); + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + + assertLdapConnectorInstances(2); + } + + @Test + public void test390ModifyUserBarbossaRename() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta objectDelta = createModifyUserReplaceDelta(USER_BARBOSSA_OID, UserType.F_NAME, + PrismTestUtil.createPolyString(USER_CPTBARBOSSA_USERNAME)); + objectDelta.addModificationReplaceProperty(UserType.F_FULL_NAME, + PrismTestUtil.createPolyString(USER_CPTBARBOSSA_FULL_NAME)); + Collection> deltas = MiscSchemaUtil.createCollection(objectDelta); + + // WHEN + when(); + modelService.executeChanges(deltas, null, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); + assertAttribute(entry, "title", "Captain"); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + PrismObject shadow = getObject(ShadowType.class, shadowOid); + display("Shadow after rename (model)", shadow); + + PrismObject repoShadow = repositoryService.getObject(ShadowType.class, shadowOid, null, result); + display("Shadow after rename (repo)", repoShadow); + + assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + + assertLdapConnectorInstances(2); + } + + // TODO: create account with a group membership + + @Test + public void test395UnAssignBarbossaPirates() throws Exception { + // TODO: do this on another account. There is a bad interference with rename. + + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + unassignRole(USER_BARBOSSA_OID, ROLE_PIRATES_OID, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + Entry entry = assertLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); + display("Entry", entry); + assertAttribute(entry, "title", "Captain"); + + assertLdapNoGroupMember(entry, GROUP_PIRATES_NAME); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + PrismObject shadow = getObject(ShadowType.class, shadowOid); + IntegrationTestTools.assertNoAssociation(shadow, getAssociationGroupQName(), groupPiratesOid); + + assertLdapConnectorInstances(2); + } + + @Test + public void test399UnAssignAccountBarbossa() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + unassignAccountFromUser(USER_BARBOSSA_OID, getResourceOid(), null, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + assertNoLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertNoLdapAccount(USER_CPTBARBOSSA_USERNAME, USER_CPTBARBOSSA_FULL_NAME); + + PrismObject user = getUser(USER_BARBOSSA_OID); + assertNoLinkedAccount(user); + + assertLdapConnectorInstances(2); + } + + @Test + public void test500AddOrgMeleeIsland() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + PrismObject org = prismContext.getSchemaRegistry().findObjectDefinitionByCompileTimeClass(OrgType.class).instantiate(); + OrgType orgType = org.asObjectable(); + orgType.setName(new PolyStringType(GROUP_MELEE_ISLAND_NAME)); + AssignmentType metaroleAssignment = new AssignmentType(); + ObjectReferenceType metaroleRef = new ObjectReferenceType(); + metaroleRef.setOid(ROLE_META_ORG_OID); + metaroleRef.setType(RoleType.COMPLEX_TYPE); + metaroleAssignment.setTargetRef(metaroleRef); + orgType.getAssignment().add(metaroleAssignment); + + // WHEN + when(); + addObject(org, task, result); + + // THEN + then(); + result.computeStatus(); + TestUtil.assertSuccess(result); + + orgMeleeIslandOid = org.getOid(); + assertLdapGroup(GROUP_MELEE_ISLAND_NAME); + + org = getObject(OrgType.class, orgMeleeIslandOid); + groupMeleeOid = getSingleLinkOid(org); + PrismObject shadow = getShadowModel(groupMeleeOid); + display("Shadow (model)", shadow); + + assertLdapConnectorInstances(2); + } + + @Test + public void test510AssignGuybrushMeleeIsland() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + // WHEN + when(); + assignOrg(USER_GUYBRUSH_OID, orgMeleeIslandOid, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_GUYBRUSH_USERNAME, USER_GUYBRUSH_FULL_NAME); + + PrismObject user = getUser(USER_GUYBRUSH_OID); + String shadowOid = getSingleLinkOid(user); + PrismObject shadow = getShadowModel(shadowOid); + display("Shadow (model)", shadow); + + assertLdapGroupMember(entry, GROUP_MELEE_ISLAND_NAME); + + IntegrationTestTools.assertAssociation(shadow, getAssociationGroupQName(), groupMeleeOid); + + assertLdapConnectorInstances(2); + } + + @Override + protected void doAdditionalRenameModifications(LdapNetworkConnection connection) throws LdapException { + Modification mod = new DefaultModification(ModificationOperation.REPLACE_ATTRIBUTE, + ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, ACCOUNT_HTM_UID); + connection.modify(toAccountDn(ACCOUNT_HTM_UID, ACCOUNT_HTM_CN), mod); + display("Modified " + toAccountDn(ACCOUNT_HT_UID, ACCOUNT_HT_CN) + " " + ATTRIBUTE_SAM_ACCOUNT_NAME_NAME + + " -> " + ACCOUNT_HTM_UID + ": " + mod); + } + + @Override + protected String getAccountHtmCnAfterRename() { + return ACCOUNT_HTM_CN; + } + + @Override + protected void assertAccountShadow(PrismObject shadow, String dn) throws SchemaException { + super.assertAccountShadow(shadow, dn); + ResourceAttribute primaryIdAttr = ShadowUtil.getAttribute(shadow, getPrimaryIdentifierAttributeQName()); + assertNotNull("No primary identifier (" + getPrimaryIdentifierAttributeQName() + " in " + shadow, primaryIdAttr); + String primaryId = primaryIdAttr.getRealValue(); + assertTrue("Unexpected chars in primary ID: '" + primaryId + "'", primaryId.matches("[a-z0-9\\-]+")); + } + + @Override + protected Entry assertLdapAccount(String samAccountName, String cn) throws LdapException, IOException, CursorException { + Entry entry = searchLdapAccount("(cn=" + cn + ")"); + assertAttribute(entry, "cn", cn); + assertAttribute(entry, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName); + return entry; + } + + @Override + protected void assertNoLdapAccount(String uid) { + throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); + } + + protected void assertNoLdapAccount(String uid, String cn) throws LdapException, IOException, CursorException { + LdapNetworkConnection connection = ldapConnect(); + List entriesCn = ldapSearch(connection, "(cn=" + cn + ")"); + List entriesSamAccountName = ldapSearch(connection, "(sAMAccountName=" + uid + ")"); + ldapDisconnect(connection); + + assertEquals("Unexpected number of entries for cn=" + cn + ": " + entriesCn, 0, entriesCn.size()); + assertEquals("Unexpected number of entries for sAMAccountName=" + uid + ": " + entriesSamAccountName, 0, entriesSamAccountName.size()); + } + + @Override + protected String toAccountDn(String username) { + throw new UnsupportedOperationException("Boom! Cannot do this here. This is bloody AD! We need full name!"); + } + + @Override + protected String toAccountDn(String username, String fullName) { + return "CN=" + fullName + "," + getPeopleLdapSuffix(); + } + + @Override + protected Rdn toAccountRdn(String username, String fullName) { + try { + return new Rdn(new Ava("CN", fullName)); + } catch (LdapInvalidDnException e) { + throw new IllegalStateException(e.getMessage(), e); + } + } + + protected void assertLdapPasswordByFullName(String fullName, String password) + throws LdapException, IOException, CursorException { + Entry entry = getLdapAccountByCn(fullName); + assertLdapPassword(entry, password); + } + + protected void assertLdapPassword(String uid, String password) { + throw new UnsupportedOperationException( + "Boom! Cannot do this here. This is bloody AD! We need full name!"); + } + + protected ObjectQuery createSamAccountNameQuery(String samAccountName) throws SchemaException { + ObjectQuery query = ObjectQueryUtil.createResourceAndObjectClassQuery(getResourceOid(), getAccountObjectClass(), prismContext); + ObjectQueryUtil.filterAnd(query.getFilter(), createAttributeFilter(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, samAccountName), + prismContext); + return query; + } + + @Override + protected Entry createAccountEntry(String uid, String cn, String givenName, String sn) throws LdapException { + byte[] password = encodePassword("Secret.123"); + Entry entry = new DefaultEntry(toAccountDn(uid, cn), + "objectclass", getLdapAccountObjectClass(), + ATTRIBUTE_SAM_ACCOUNT_NAME_NAME, uid, + "cn", cn, + "givenName", givenName, + "sn", sn, + ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512", + ATTRIBUTE_UNICODE_PWD_NAME, password); + return entry; + } + + private byte[] encodePassword(String password) { + String quotedPassword = "\"" + password + "\""; + return quotedPassword.getBytes(StandardCharsets.UTF_16LE); + } + + @Override + protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) + throws ObjectNotFoundException, SchemaException { + OperationResult result = createOperationResult("assertStepSyncToken"); + Task task = taskManager.getTask(syncTaskOid, result); + PrismProperty syncTokenProperty = task.getExtensionPropertyOrClone(SchemaConstants.SYNC_TOKEN); + assertNotNull("No sync token", syncTokenProperty); + assertNotNull("No sync token value", syncTokenProperty.getRealValue()); + assertNotNull("Empty sync token value", StringUtils.isBlank(syncTokenProperty.getRealValue())); + assertSuccess(result); + } + + public void assertAttribute(PrismObject shadow, String attrName, T... expectedValues) { + assertAttribute(shadow, new QName(getResourceNamespace(), attrName), expectedValues); + } + + public void assertAttribute(PrismObject shadow, QName attrQname, T... expectedValues) { + List actualValues = ShadowUtil.getAttributeValues(shadow, attrQname); + PrismAsserts.assertSets("attribute " + attrQname + " in " + shadow, actualValues, expectedValues); + } + + protected abstract void assertAccountDisabled(PrismObject shadow); + + protected abstract void assertAccountEnabled(PrismObject shadow); +} diff --git a/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml b/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml index 7d17493139a..2b43b0addf6 100644 --- a/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml +++ b/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml @@ -1,855 +1,856 @@ - - - - Active Directory Chimera (LDAP) - - - - - c:connectorType - com.evolveum.polygon.connector.ldap.ad.AdLdapConnector - - - - - - - chimera.ad.evolveum.com - 636 - adBaseDn - CN=midpoint,CN=Users,DC=ad,DC=evolveum,DC=com - ssl - - qwe.123 - - host=hydra.ad.evolveum.com; baseContext=DC=sub,DC=ad,DC=evolveum,DC=com; bindDn=CN=midpoint,CN=Users,DC=sub,DC=ad,DC=evolveum,DC=com - ignore - resolve - msExchHideFromAddressLists - true - false - always - - - false - false - false - - - - - powershell - - - - c:connectorType - com.evolveum.polygon.connector.powershell.PowerShellConnector - - - - - - chimera.ad.evolveum.com - midpoint - - qwe.123 - - midpoint - credssp - 5986 - true - variables - - - false - false - false - - - - - - - ri:user - ri:group - ri:organizationalUnit - ri:domain - ri:msExchBaseClass - - - - - - - - account - Default Account - true - ri:user - - ri:organizationalUnit - - - attributes/dn - adUsersDn - - - - - ri:dn - Distinguished Name - mr:distinguishedName - - - fullName - - - - - - - - - ri:sAMAccountName - Login name - true - - - name - - - - - name - - - - - - ri:cn - - 0 - - - - fullName - - - - - fullName - - - - - - ri:sn - - 0 - - - - familyName - - - - - familyName - - - - - - ri:givenName - - - givenName - - - - - givenName - - - - - - ri:title - - - title - - - - - - ri:userPrincipalName - - - name - - - - - - - - - ri:pwdLastSet - - - -1 - - - - - - ri:createTimeStamp - explicit - - - - ri:objectCategory - - - CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com - - - - - - ri:showInAdvancedViewOnly - - - extension/showInAdvancedViewOnly - - - - - - ri:msExchHideFromAddressLists - MID-4041 - - strong - - activation/effectiveStatus - - - - - - - - - ri:group - AD Group Membership - entitlement - group - objectToSubject - ri:member - ri:dn - ri:memberOf - ri:dn - false - - - - ri:org-group - AD Org Group Membership - entitlement - org-group - objectToSubject - ri:member - ri:dn - ri:memberOf - ri:dn - false - - - - - - attributes/dn - cn=midpoint,cn=users,dc=ad,dc=evolveum,dc=com - - - - - - - attributes/dn - CN=SUB$,CN=Users,DC=ad,DC=evolveum,DC=com - - - - - - - attributes/dn - CN=DiscoverySearchMailbox - true - - - - - - - attributes/dn - CN=SystemMailbox - true - - - - - - - - - - - - - - - - - - - - generic - ou-top - Top Org - true - ri:organizationalUnit - - ri:organizationalUnit - - - attributes/dn - OU=Org,DC=ad,DC=evolveum,DC=com - - - - - ri:dn - Distinguished Name - mr:distinguishedName - - - name - - - - - - - - - ri:ou - - 0 - - - - name - - - - - - - ri:objectCategory - - - CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com - - - - - - - - - account - sub - Sub Account - false - ri:user - - ri:organizationalUnit - - - attributes/dn - CN=Users,DC=sub,DC=ad,DC=evolveum,DC=com - - - - - ri:dn - Distinguished Name - mr:distinguishedName - - - $user/fullName - - - - - - - - - ri:sAMAccountName - Login name - - - $user/name - - - - - name - - - - - - ri:cn - - 0 - - - - fullName - - - - - fullName - - - - - - ri:sn - - 0 - - - - familyName - - - - - familyName - - - - - - ri:givenName - - - givenName - - - - - givenName - - - - - - ri:title - - - title - - - - - - ri:userPrincipalName - - - $user/name - - - - - - - - - ri:pwdLastSet - - - -1 - - - - - - ri:createTimeStamp - explicit - - - - ri:nTSecurityDescriptor - - - 0 - - - - - ri:instanceType - - - 0 - - - - - ri:objectCategory - - - 0 - - - - CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com - - - - - - - ri:group - AD Group Membership - entitlement - group - objectToSubject - ri:member - ri:dn - ri:memberOf - ri:dn - false - - - - - - - - - - - - - - - - - - generic - ou-sub - Sub Org - ri:organizationalUnit - - ri:domain - - - attributes/dn - DC=sub,DC=ad,DC=evolveum,DC=com - - - - - ri:dn - Distinguished Name - mr:distinguishedName - - - name - - - - - - - - - ri:ou - - 0 - - - - name - - - - - - - ri:objectCategory - - - CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com - - - - - - - - - entitlement - group - AD Group - Groups in the parent (top) domain - true - ri:group - - ri:organizationalUnit - - - attributes/dn - CN=Users,DC=ad,DC=evolveum,DC=com - - - - - dn - mr:distinguishedName - - - $focus/name - - - - - - - - ri:cn - mr:stringIgnoreCase - - - $focus/name - - - - - name - - - - - ri:description - - strong - - description - - - - - description - - - - - - - entitlement - org-group - Organizational Group - Groups in the parent (top) domain that are part of organizational units - false - ri:group - - ri:organizationalUnit - - - attributes/dn - OU=Org,DC=ad,DC=evolveum,DC=com - - - - - dn - mr:distinguishedName - - - $focus/name - - - - - - - - ri:cn - mr:stringIgnoreCase - - - $focus/name - - - - - name - - - - - ri:description - - strong - - description - - - - - description - - - - - - - - - - - - - - - true - true - - - - - - Account sync - ri:user - account - default - UserType - true - - - c:name - - $shadow/attributes/sAMAccountName - - - - - - linked - true - - - deleted - http://midpoint.evolveum.com/xml/ns/public/model/action-3#deleteFocus - - - unlinked - http://midpoint.evolveum.com/xml/ns/public/model/action-3#link - - - unmatched - http://midpoint.evolveum.com/xml/ns/public/model/action-3#addFocus - - - - - - - + + + + Active Directory Chimera (LDAP) + + + + + c:connectorType + com.evolveum.polygon.connector.ldap.ad.AdLdapConnector + + + + + + + chimera.ad.evolveum.com + 636 + adBaseDn + CN=midpoint,CN=Users,DC=ad,DC=evolveum,DC=com + ssl + + qwe.123 + + host=hydra.ad.evolveum.com; baseContext=DC=sub,DC=ad,DC=evolveum,DC=com; bindDn=CN=midpoint,CN=Users,DC=sub,DC=ad,DC=evolveum,DC=com + ignore + resolve + msExchHideFromAddressLists + true + false + always + CN=Users,DC=ad,DC=evolveum,DC=com + + + false + false + false + + + + + powershell + + + + c:connectorType + com.evolveum.polygon.connector.powershell.PowerShellConnector + + + + + + chimera.ad.evolveum.com + midpoint + + qwe.123 + + midpoint + credssp + 5986 + true + variables + + + false + false + false + + + + + + + ri:user + ri:group + ri:organizationalUnit + ri:domain + ri:msExchBaseClass + + + + + + + + account + Default Account + true + ri:user + + ri:organizationalUnit + + + attributes/dn + adUsersDn + + + + + ri:dn + Distinguished Name + mr:distinguishedName + + + fullName + + + + + + + + + ri:sAMAccountName + Login name + true + + + name + + + + + name + + + + + + ri:cn + + 0 + + + + fullName + + + + + fullName + + + + + + ri:sn + + 0 + + + + familyName + + + + + familyName + + + + + + ri:givenName + + + givenName + + + + + givenName + + + + + + ri:title + + + title + + + + + + ri:userPrincipalName + + + name + + + + + + + + + ri:pwdLastSet + + + -1 + + + + + + ri:createTimeStamp + explicit + + + + ri:objectCategory + + + CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com + + + + + + ri:showInAdvancedViewOnly + + + extension/showInAdvancedViewOnly + + + + + + ri:msExchHideFromAddressLists + MID-4041 + + strong + + activation/effectiveStatus + + + + + + + + + ri:group + AD Group Membership + entitlement + group + objectToSubject + ri:member + ri:dn + ri:memberOf + ri:dn + false + + + + ri:org-group + AD Org Group Membership + entitlement + org-group + objectToSubject + ri:member + ri:dn + ri:memberOf + ri:dn + false + + + + + + attributes/dn + cn=midpoint,cn=users,dc=ad,dc=evolveum,dc=com + + + + + + + attributes/dn + CN=SUB$,CN=Users,DC=ad,DC=evolveum,DC=com + + + + + + + attributes/dn + CN=DiscoverySearchMailbox + true + + + + + + + attributes/dn + CN=SystemMailbox + true + + + + + + + + + + + + + + + + + + + + generic + ou-top + Top Org + true + ri:organizationalUnit + + ri:organizationalUnit + + + attributes/dn + OU=Org,DC=ad,DC=evolveum,DC=com + + + + + ri:dn + Distinguished Name + mr:distinguishedName + + + name + + + + + + + + + ri:ou + + 0 + + + + name + + + + + + + ri:objectCategory + + + CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com + + + + + + + + + account + sub + Sub Account + false + ri:user + + ri:organizationalUnit + + + attributes/dn + CN=Users,DC=sub,DC=ad,DC=evolveum,DC=com + + + + + ri:dn + Distinguished Name + mr:distinguishedName + + + $user/fullName + + + + + + + + + ri:sAMAccountName + Login name + + + $user/name + + + + + name + + + + + + ri:cn + + 0 + + + + fullName + + + + + fullName + + + + + + ri:sn + + 0 + + + + familyName + + + + + familyName + + + + + + ri:givenName + + + givenName + + + + + givenName + + + + + + ri:title + + + title + + + + + + ri:userPrincipalName + + + $user/name + + + + + + + + + ri:pwdLastSet + + + -1 + + + + + + ri:createTimeStamp + explicit + + + + ri:nTSecurityDescriptor + + + 0 + + + + + ri:instanceType + + + 0 + + + + + ri:objectCategory + + + 0 + + + + CN=Person,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com + + + + + + + ri:group + AD Group Membership + entitlement + group + objectToSubject + ri:member + ri:dn + ri:memberOf + ri:dn + false + + + + + + + + + + + + + + + + + + generic + ou-sub + Sub Org + ri:organizationalUnit + + ri:domain + + + attributes/dn + DC=sub,DC=ad,DC=evolveum,DC=com + + + + + ri:dn + Distinguished Name + mr:distinguishedName + + + name + + + + + + + + + ri:ou + + 0 + + + + name + + + + + + + ri:objectCategory + + + CN=Organizational-Unit,CN=Schema,CN=Configuration,DC=ad,DC=evolveum,DC=com + + + + + + + + + entitlement + group + AD Group + Groups in the parent (top) domain + true + ri:group + + ri:organizationalUnit + + + attributes/dn + CN=Users,DC=ad,DC=evolveum,DC=com + + + + + dn + mr:distinguishedName + + + $focus/name + + + + + + + + ri:cn + mr:stringIgnoreCase + + + $focus/name + + + + + name + + + + + ri:description + + strong + + description + + + + + description + + + + + + + entitlement + org-group + Organizational Group + Groups in the parent (top) domain that are part of organizational units + false + ri:group + + ri:organizationalUnit + + + attributes/dn + OU=Org,DC=ad,DC=evolveum,DC=com + + + + + dn + mr:distinguishedName + + + $focus/name + + + + + + + + ri:cn + mr:stringIgnoreCase + + + $focus/name + + + + + name + + + + + ri:description + + strong + + description + + + + + description + + + + + + + + + + + + + + + true + true + + + + + + Account sync + ri:user + account + default + UserType + true + + + c:name + + $shadow/attributes/sAMAccountName + + + + + + linked + true + + + deleted + http://midpoint.evolveum.com/xml/ns/public/model/action-3#deleteFocus + + + unlinked + http://midpoint.evolveum.com/xml/ns/public/model/action-3#link + + + unmatched + http://midpoint.evolveum.com/xml/ns/public/model/action-3#addFocus + + + + + + + diff --git a/testing/conntest/src/test/resources/ad-ldap-multidomain/task-sync.xml b/testing/conntest/src/test/resources/ad-ldap-multidomain/task-sync.xml new file mode 100644 index 00000000000..f6a92fda7fb --- /dev/null +++ b/testing/conntest/src/test/resources/ad-ldap-multidomain/task-sync.xml @@ -0,0 +1,28 @@ + + + + + + Synchronization: Active Directory Chimera (LDAP) + + 0f93d8d4-5fb4-11ea-8571-a3f090bf921f + + runnable + + http://midpoint.evolveum.com/xml/ns/public/model/synchronization/task/live-sync/handler-3 + + recurring + + 3 + + + diff --git a/testing/conntest/src/test/resources/logback-test.xml b/testing/conntest/src/test/resources/logback-test.xml index 69f46a4eb5a..fc529df964b 100644 --- a/testing/conntest/src/test/resources/logback-test.xml +++ b/testing/conntest/src/test/resources/logback-test.xml @@ -1,68 +1,73 @@ - - - - - - - - - ./target/test.log - - - %date [%thread] %-5level [%X{subsystem}]\(%logger{46}\): %message%n - - - - - %date [%thread] %-5level \(%logger{46}\): %message%n - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - + + + + + + + + + ./target/test.log + + + %date [%thread] %-5level [%X{subsystem}]\(%logger{46}\): %message%n + + + + + %date [%thread] %-5level \(%logger{46}\): %message%n + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + From 924b656246171ee69e93b1f301dce23fc4d0d50f Mon Sep 17 00:00:00 2001 From: Katarina Valalikova Date: Mon, 9 Mar 2020 12:01:53 +0100 Subject: [PATCH 37/55] rename TaskTabPanel -> RefreshableTabPanel, fixing refresh on task details for wrapper tabs, fixing enable behavior for referencePanel --- .../midpoint/gui/impl/prism/ItemPanel.java | 11 ++++- .../gui/impl/prism/PrismReferencePanel.java | 10 ++--- .../web/page/admin/server/PageTask.java | 6 +-- ...TabPanel.java => RefreshableTabPanel.java} | 40 +++++++++---------- .../page/admin/server/TaskErrorsTabPanel.java | 2 +- .../TaskInternalPerformanceTabPanel.java | 2 +- .../server/TaskOperationStatisticsPanel.java | 6 +-- .../admin/server/TaskOperationTabPanel.java | 2 +- .../admin/server/TaskPerformanceTabPanel.java | 2 +- .../page/admin/server/TaskResultTabPanel.java | 2 +- .../TaskSubtasksAndThreadsTabPanel.java | 2 +- 11 files changed, 43 insertions(+), 42 deletions(-) rename gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/{TaskTabPanel.java => RefreshableTabPanel.java} (87%) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemPanel.java index bdfaea97578..423561f6e92 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/ItemPanel.java @@ -6,10 +6,14 @@ */ package com.evolveum.midpoint.gui.impl.prism; +import java.util.Collection; +import java.util.Collections; import java.util.List; import com.evolveum.midpoint.prism.PrismValue; +import com.evolveum.midpoint.web.page.admin.server.RefreshableTabPanel; + import org.apache.wicket.AttributeModifier; import org.apache.wicket.Component; import org.apache.wicket.ajax.AjaxRequestTarget; @@ -37,7 +41,7 @@ * @author katka * */ -public abstract class ItemPanel extends BasePanel{ +public abstract class ItemPanel extends BasePanel implements RefreshableTabPanel { private static final long serialVersionUID = 1L; @@ -314,4 +318,9 @@ protected boolean isHeaderVisible() { public ItemPanelSettings getSettings() { return itemPanelSettings; } + + @Override + public Collection getComponentsToUpdate() { + return Collections.singleton(this); + } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismReferencePanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismReferencePanel.java index 9e8e5dd2221..a1ff5b5eb33 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismReferencePanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismReferencePanel.java @@ -154,14 +154,12 @@ protected void addValue(AjaxRequestTarget target) { target.add(PrismReferencePanel.this); } - -// @Override -// protected EnableBehaviour getEnableBehaviourOfValuePanel(PrismReferenceWrapper iw) { -// return new EnableBehaviour(() -> !iw.isReadOnly() || isLink(iw)); -// } - + @Override public boolean isEnabled() { + if (getEditabilityHandler() != null && !getEditabilityHandler().isEditable(getModelObject())) { + return false; + } return !getModelObject().isReadOnly() || isLink(getModelObject()); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java index 039aaecd5eb..d71d2265a0c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java @@ -6,8 +6,6 @@ import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; import com.evolveum.midpoint.report.api.ReportConstants; -import com.evolveum.midpoint.report.api.ReportManager; -import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.web.component.AjaxDownloadBehaviorFromStream; import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; @@ -520,9 +518,9 @@ public void refresh(AjaxRequestTarget target) { // target.add(getMainPanel()); for (Component component : getMainPanel().getTabbedPanel()) { - if (component instanceof TaskTabPanel) { + if (component instanceof RefreshableTabPanel) { - for (Component c : ((TaskTabPanel) component).getComponentsToUpdate()) { + for (Component c : ((RefreshableTabPanel) component).getComponentsToUpdate()) { target.add(c); } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/RefreshableTabPanel.java similarity index 87% rename from gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabPanel.java rename to gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/RefreshableTabPanel.java index 422d26ceadf..38498ddaa72 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/RefreshableTabPanel.java @@ -1,20 +1,20 @@ -/* - * Copyright (c) 2010-2017 Evolveum and contributors - * - * This work is dual-licensed under the Apache License 2.0 - * and European Union Public License. See LICENSE file for details. - */ - -package com.evolveum.midpoint.web.page.admin.server; - -import org.apache.wicket.Component; - -import java.util.Collection; - -/** - * @author mederly - */ -@FunctionalInterface -public interface TaskTabPanel { - Collection getComponentsToUpdate(); -} +/* + * Copyright (c) 2010-2017 Evolveum and contributors + * + * This work is dual-licensed under the Apache License 2.0 + * and European Union Public License. See LICENSE file for details. + */ + +package com.evolveum.midpoint.web.page.admin.server; + +import org.apache.wicket.Component; + +import java.util.Collection; + +/** + * @author mederly + */ +@FunctionalInterface +public interface RefreshableTabPanel { + Collection getComponentsToUpdate(); +} diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskErrorsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskErrorsTabPanel.java index c16dc922dac..b93b1b4b457 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskErrorsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskErrorsTabPanel.java @@ -44,7 +44,7 @@ /** * Created by honchar. */ -public class TaskErrorsTabPanel extends BasePanel> implements TaskTabPanel { +public class TaskErrorsTabPanel extends BasePanel> implements RefreshableTabPanel { private static final long serialVersionUID = 1L; private static final String ID_TASK_ERRORS = "taskErrors"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskInternalPerformanceTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskInternalPerformanceTabPanel.java index 6fc80a328f2..00989286192 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskInternalPerformanceTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskInternalPerformanceTabPanel.java @@ -26,7 +26,7 @@ /** * */ -public class TaskInternalPerformanceTabPanel extends BasePanel> implements TaskTabPanel { +public class TaskInternalPerformanceTabPanel extends BasePanel> implements RefreshableTabPanel { private static final long serialVersionUID = 1L; private static final transient Trace LOGGER = TraceManager.getTrace(TaskInternalPerformanceTabPanel.class); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java index 974cfaa0044..b0fc03d8c46 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java @@ -10,9 +10,6 @@ import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.schema.constants.ObjectTypes; import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.schema.statistics.ActionsExecutedInformation; -import com.evolveum.midpoint.schema.statistics.IterativeTaskInformation; -import com.evolveum.midpoint.schema.statistics.SynchronizationInformation; import com.evolveum.midpoint.schema.util.TaskTypeUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskCategory; @@ -37,9 +34,8 @@ import java.util.Arrays; import java.util.Collection; import java.util.List; -import java.util.stream.Stream; -public class TaskOperationStatisticsPanel extends BasePanel> implements TaskTabPanel { +public class TaskOperationStatisticsPanel extends BasePanel> implements RefreshableTabPanel { private static final String ID_PROCESSING_INFO = "processingInfo"; private static final String ID_SYNCHORNIZATION_SITUATIONS = "synchronizationSituation"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationTabPanel.java index 025c6963cf2..251d6a1aabd 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationTabPanel.java @@ -37,7 +37,7 @@ */ //TODO implement correctly -public class TaskOperationTabPanel extends BasePanel> implements TaskTabPanel { +public class TaskOperationTabPanel extends BasePanel> implements RefreshableTabPanel { private static final long serialVersionUID = 1L; private static final String ID_MODEL_OPERATION_STATUS_PANEL = "modelOperationStatusPanel"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskPerformanceTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskPerformanceTabPanel.java index 2755e10cde5..167259272c4 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskPerformanceTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskPerformanceTabPanel.java @@ -24,7 +24,7 @@ /** * @author semancik */ -public class TaskPerformanceTabPanel extends BasePanel> implements TaskTabPanel { +public class TaskPerformanceTabPanel extends BasePanel> implements RefreshableTabPanel { private static final long serialVersionUID = 1L; private static final String ID_STATISTICS_PANEL = "statisticsPanel"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskResultTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskResultTabPanel.java index 1d5f67bc2a6..86c56b0bf6b 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskResultTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskResultTabPanel.java @@ -39,7 +39,7 @@ /** * @author semancik */ -public class TaskResultTabPanel extends BasePanel> implements TaskTabPanel { +public class TaskResultTabPanel extends BasePanel> implements RefreshableTabPanel { private static final long serialVersionUID = 1L; private static final String ID_OPERATION_RESULT = "operationResult"; diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSubtasksAndThreadsTabPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSubtasksAndThreadsTabPanel.java index 808b0d6d95b..6228d0adff2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSubtasksAndThreadsTabPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskSubtasksAndThreadsTabPanel.java @@ -30,7 +30,7 @@ /** * @author semancik */ -public class TaskSubtasksAndThreadsTabPanel extends BasePanel> implements TaskTabPanel { +public class TaskSubtasksAndThreadsTabPanel extends BasePanel> implements RefreshableTabPanel { private static final long serialVersionUID = 1L; private static final String ID_WORKER_THREADS_TABLE = "workerThreadsTable"; From ffaf79e8f9f7b714807ab146e4ce04a940e84a6d Mon Sep 17 00:00:00 2001 From: Radovan Semancik Date: Mon, 9 Mar 2020 13:56:26 +0100 Subject: [PATCH 38/55] baseContextsToSynchronize -> baseContextToSynchronize (MID-5942) --- pom.xml | 2 +- .../conntest/ad/AbstractAdLdapMultidomainTest.java | 8 ++++++-- .../resources/ad-ldap-multidomain/resource-chimera.xml | 2 +- 3 files changed, 8 insertions(+), 4 deletions(-) diff --git a/pom.xml b/pom.xml index bd49a078ecd..b9064b88a29 100644 --- a/pom.xml +++ b/pom.xml @@ -892,7 +892,7 @@ com.evolveum.polygon connector-ldap - 3.0-M1 + 3.0-SNAPSHOT diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java index 0dd0e22f648..ad3fa327405 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java @@ -2138,7 +2138,9 @@ public void test850ReconcileAccounts() throws Exception { // assertLdapConnectorInstances(2); } - @Test + // DISABLED because we do not know how to properly configure sync privileges in a AD forrest. + // More experiments are needed, but only after we migrate our old AD servers. + @Test(enabled=false) public void test900ImportSyncTask() throws Exception { // GIVEN Task task = getTestTask(); @@ -2161,7 +2163,9 @@ public void test900ImportSyncTask() throws Exception { assertStepSyncToken(getSyncTaskOid(), 0, tsStart, tsEnd); } - @Test + // DISABLED because we do not know how to properly configure sync privileges in a AD forrest. + // More experiments are needed, but only after we migrate our old AD servers. + @Test(enabled=false) public void test901SyncAddAccountHt() throws Exception { // GIVEN Task task = getTestTask(); diff --git a/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml b/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml index 2b43b0addf6..742e93e16da 100644 --- a/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml +++ b/testing/conntest/src/test/resources/ad-ldap-multidomain/resource-chimera.xml @@ -41,7 +41,7 @@ true false always - CN=Users,DC=ad,DC=evolveum,DC=com + CN=Users,DC=ad,DC=evolveum,DC=com false From 2bf522bcb19e6ff44219b9ec6d3ff3db760374d2 Mon Sep 17 00:00:00 2001 From: Radovan Semancik Date: Mon, 9 Mar 2020 15:20:14 +0100 Subject: [PATCH 39/55] Test to reproduce MID-4385: can't reproduce --- .../ad/AbstractAdLdapMultidomainTest.java | 46 ++ .../testing/conntest/ad/AdTestMixin.java | 505 +++++++++--------- 2 files changed, 299 insertions(+), 252 deletions(-) diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java index ad3fa327405..537362e9d1d 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java @@ -154,6 +154,8 @@ public abstract class AbstractAdLdapMultidomainTest extends AbstractLdapTest private static final String USER_GUYBRUSH_PASSWORD_123 = "wanna.be.a.123"; private static final String USER_GUYBRUSH_PASSWORD_333 = "wanna.be.a.333"; + private static final String VERY_STRANGE_PARAMETER = "This iš a véry stándže p§räméteř!"; + private boolean allowDuplicateSearchResults = false; protected String jackAccountOid; @@ -951,6 +953,50 @@ public void test214ModifyAccountBarbossaProxyAddressesSimple() throws Exception String shadowOid = getSingleLinkOid(user); assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); +// assertLdapConnectorInstances(2); + } + + /** + * MID-4385 + */ + @Test + public void test216ModifyAccountBarbossaUserParameters() throws Exception { + // GIVEN + Task task = getTestTask(); + OperationResult result = task.getResult(); + + ObjectDelta delta = prismContext.deltaFactory().object() + .createEmptyModifyDelta(ShadowType.class, accountBarbossaOid); + QName attrQName = new QName(MidPointConstants.NS_RI, ATTRIBUTE_USER_PARAMETERS_NAME); + ResourceAttributeDefinition attrDef = accountObjectClassDefinition.findAttributeDefinition(attrQName); + assertNotNull("No definition for attribute " + attrQName, attrDef); + PropertyDelta attrDelta = prismContext.deltaFactory().property().createModificationReplaceProperty( + ItemPath.create(ShadowType.F_ATTRIBUTES, attrQName), attrDef, VERY_STRANGE_PARAMETER); + delta.addModification(attrDelta); + + // WHEN + when(); + executeChanges(delta, null, task, result); + + // THEN + then(); + assertSuccess(result); + + Entry entry = assertLdapAccount(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME); + assertAttribute(entry, ATTRIBUTE_USER_PARAMETERS_NAME, VERY_STRANGE_PARAMETER); + assertAttribute(entry, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME, "512"); + assertAttribute(entry, ATTRIBUTE_OBJECT_CATEGORY_NAME, OBJECT_CATEGORY_PERSON); + assertLdapPassword(USER_BARBOSSA_USERNAME, USER_BARBOSSA_FULL_NAME, USER_BARBOSSA_PASSWORD); + + PrismObject user = getUser(USER_BARBOSSA_OID); + String shadowOid = getSingleLinkOid(user); + assertEquals("Shadows have moved", accountBarbossaOid, shadowOid); + + assertModelShadow(shadowOid) + .attributes() + .attribute(ATTRIBUTE_USER_PARAMETERS_NAME) + .assertRealValues(VERY_STRANGE_PARAMETER); + // assertLdapConnectorInstances(2); } diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java index 514bf27c05c..e787b5dd63c 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AdTestMixin.java @@ -1,252 +1,253 @@ -/* - * Copyright (c) 2016 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.testing.conntest.ad; - -import static org.testng.AssertJUnit.*; - -import javax.xml.namespace.QName; - -import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; -import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; -import com.evolveum.midpoint.prism.PrimitiveType; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.util.PrismAsserts; -import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; -import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; -import com.evolveum.midpoint.schema.processor.ResourceSchema; -import com.evolveum.midpoint.schema.util.ResourceTypeUtil; -import com.evolveum.midpoint.tools.testng.MidpointTestMixin; -import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.util.DebugDumpable; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; - -/** - * Mixin providing common methods/utilities for Active Directory (AD) related tests. - */ -public interface AdTestMixin extends MidpointTestMixin { - - String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; - String ATTRIBUTE_OBJECT_SID_NAME = "objectSid"; - String ATTRIBUTE_OBJECT_CATEGORY_NAME = "objectCategory"; - String ATTRIBUTE_SAM_ACCOUNT_NAME_NAME = "sAMAccountName"; - String ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME = "userAccountControl"; - QName ATTRIBUTE_USER_ACCOUNT_CONTROL_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME); - String ATTRIBUTE_UNICODE_PWD_NAME = "unicodePwd"; - String ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME = "msExchHideFromAddressLists"; - QName ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); - String ATTRIBUTE_TITLE_NAME = "title"; - String ATTRIBUTE_PROXY_ADDRESSES_NAME = "proxyAddresses"; - - QName OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME = new QName(MidPointConstants.NS_RI, "msExchBaseClass"); - - String AD_CONNECTOR_TYPE = "com.evolveum.polygon.connector.ldap.ad.AdLdapConnector"; - - /** - * Returns dashed GUID notation formatted from simple hex-encoded binary. - *

- * E.g. "2f01c06bb1d0414e9a69dd3841a13506" -> "6bc0012f-d0b1-4e41-9a69-dd3841a13506" - */ - default String formatGuidToDashedNotation(String hexValue) { - if (hexValue == null) { - return null; - } - return hexValue.substring(6, 8) - + hexValue.substring(4, 6) - + hexValue.substring(2, 4) - + hexValue.substring(0, 2) - + '-' - + hexValue.substring(10, 12) - + hexValue.substring(8, 10) - + '-' - + hexValue.substring(14, 16) - + hexValue.substring(12, 14) - + '-' - + hexValue.substring(16, 20) - + '-' - + hexValue.substring(20, 32); - } - - default ObjectClassComplexTypeDefinition assertAdResourceSchema( - PrismObject resource, QName accountObjectClass, PrismContext prismContext) - throws SchemaException { - ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); - display("Resource schema", resourceSchema); - ResourceTypeUtil.validateSchema(resourceSchema, resource); - return assertAdSchema(resource, accountObjectClass); - } - - default ObjectClassComplexTypeDefinition assertAdResourceSchemaLongTimestamp( - PrismObject resource, QName accountObjectClass, PrismContext prismContext) - throws SchemaException { - ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); - display("Resource schema", resourceSchema); - ResourceTypeUtil.validateSchema(resourceSchema, resource); - return assertAdSchemaLongTimestamp(resource, accountObjectClass); - } - - default ObjectClassComplexTypeDefinition assertAdRefinedSchema( - PrismObject resource, QName accountObjectClass) throws SchemaException { - RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); - display("Refined schema", refinedSchema); - RefinedResourceSchemaImpl.validateRefinedSchema(refinedSchema, resource); - return assertAdSchema(resource, accountObjectClass); - } - - // Assumes string timestamp - default ObjectClassComplexTypeDefinition assertAdSchema( - PrismObject resource, QName accountObjectClass) throws SchemaException { - ObjectClassComplexTypeDefinition accountObjectClassDefinition = assertAdSchemaBase(resource, accountObjectClass); - - ResourceAttributeDefinition createTimestampDef = - accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); - PrismAsserts.assertDefinition(createTimestampDef, - new QName(MidPointConstants.NS_RI, "createTimeStamp"), DOMUtil.XSD_DATETIME, 0, 1); - assertTrue("createTimeStampDef read", createTimestampDef.canRead()); - assertFalse("createTimeStampDef modify", createTimestampDef.canModify()); - assertFalse("createTimeStampDef add", createTimestampDef.canAdd()); - - ResourceAttributeDefinition whenChangedDef = - accountObjectClassDefinition.findAttributeDefinition("whenChanged"); - PrismAsserts.assertDefinition(whenChangedDef, - new QName(MidPointConstants.NS_RI, "createTimeStamp"), DOMUtil.XSD_DATETIME, 0, 1); - assertTrue("whenChanged read", whenChangedDef.canRead()); - assertFalse("whenChanged modify", whenChangedDef.canModify()); - assertFalse("whenChanged add", whenChangedDef.canAdd()); - - return accountObjectClassDefinition; - } - - // Assumes string timestamp - default ObjectClassComplexTypeDefinition assertAdSchemaLongTimestamp( - PrismObject resource, QName accountObjectClass) throws SchemaException { - ObjectClassComplexTypeDefinition accountObjectClassDefinition = assertAdSchemaBase(resource, accountObjectClass); - - ResourceAttributeDefinition createTimestampDef = accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); - PrismAsserts.assertDefinition(createTimestampDef, new QName(MidPointConstants.NS_RI, "createTimeStamp"), - DOMUtil.XSD_LONG, 0, 1); - assertTrue("createTimeStampDef read", createTimestampDef.canRead()); - assertFalse("createTimeStampDef modify", createTimestampDef.canModify()); - assertFalse("createTimeStampDef add", createTimestampDef.canAdd()); - - return accountObjectClassDefinition; - } - - // TODO after ditching JDK 8 - /*private*/ default ObjectClassComplexTypeDefinition assertAdSchemaBase( - PrismObject resource, QName accountObjectClass) throws SchemaException { - - RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); - display("Refined schema", refinedSchema); - ObjectClassComplexTypeDefinition accountObjectClassDefinition = refinedSchema.findObjectClassDefinition(accountObjectClass); - assertNotNull("No definition for object class " + accountObjectClass, accountObjectClassDefinition); - display("Account object class def", accountObjectClassDefinition); - - ResourceAttributeDefinition cnDef = accountObjectClassDefinition.findAttributeDefinition("cn"); - PrismAsserts.assertDefinition(cnDef, new QName(MidPointConstants.NS_RI, "cn"), DOMUtil.XSD_STRING, 0, 1); - assertTrue("cn read", cnDef.canRead()); - assertTrue("cn modify", cnDef.canModify()); - assertTrue("cn add", cnDef.canAdd()); - - ResourceAttributeDefinition samAccountNameDef = accountObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME); - PrismAsserts.assertDefinition(samAccountNameDef, - new QName(MidPointConstants.NS_RI, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME), DOMUtil.XSD_STRING, 0, 1); - assertTrue("samAccountNameDef read", samAccountNameDef.canRead()); - assertTrue("samAccountNameDef modify", samAccountNameDef.canModify()); - assertTrue("samAccountNameDef add", samAccountNameDef.canAdd()); - - ResourceAttributeDefinition oDef = accountObjectClassDefinition.findAttributeDefinition("o"); - PrismAsserts.assertDefinition(oDef, new QName(MidPointConstants.NS_RI, "o"), DOMUtil.XSD_STRING, 0, -1); - assertTrue("o read", oDef.canRead()); - assertTrue("o modify", oDef.canModify()); - assertTrue("o add", oDef.canAdd()); - - ResourceAttributeDefinition isCriticalSystemObjectDef = accountObjectClassDefinition.findAttributeDefinition("isCriticalSystemObject"); - PrismAsserts.assertDefinition(isCriticalSystemObjectDef, new QName(MidPointConstants.NS_RI, "isCriticalSystemObject"), - PrimitiveType.XSD_BOOLEAN, 0, 1); - assertTrue("isCriticalSystemObject read", isCriticalSystemObjectDef.canRead()); - assertTrue("isCriticalSystemObject modify", isCriticalSystemObjectDef.canModify()); - assertTrue("isCriticalSystemObject add", isCriticalSystemObjectDef.canAdd()); - - ResourceAttributeDefinition nTSecurityDescriptorDef = accountObjectClassDefinition.findAttributeDefinition("nTSecurityDescriptor"); - PrismAsserts.assertDefinition(nTSecurityDescriptorDef, new QName(MidPointConstants.NS_RI, "nTSecurityDescriptor"), - PrimitiveType.XSD_BASE64BINARY, 0, 1); - assertTrue("nTSecurityDescriptor read", nTSecurityDescriptorDef.canRead()); - assertTrue("nTSecurityDescriptor modify", nTSecurityDescriptorDef.canModify()); - assertTrue("nTSecurityDescriptor add", nTSecurityDescriptorDef.canAdd()); - - ResourceAttributeDefinition objectSidDef = accountObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_OBJECT_SID_NAME); - PrismAsserts.assertDefinition(objectSidDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME), - PrimitiveType.XSD_STRING, 0, 1); - assertTrue("objectSid read", objectSidDef.canRead()); - assertFalse("objectSid modify", objectSidDef.canModify()); - assertFalse("objectSid add", objectSidDef.canAdd()); - - ResourceAttributeDefinition lastLogonDef = accountObjectClassDefinition.findAttributeDefinition("lastLogon"); - PrismAsserts.assertDefinition(lastLogonDef, new QName(MidPointConstants.NS_RI, "lastLogon"), - PrimitiveType.XSD_LONG, 0, 1); - assertTrue("lastLogonDef read", lastLogonDef.canRead()); - assertTrue("lastLogonDef modify", lastLogonDef.canModify()); - assertTrue("lastLogonDef add", lastLogonDef.canAdd()); - - ResourceAttributeDefinition proxyAddressesDef = accountObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_PROXY_ADDRESSES_NAME); - PrismAsserts.assertDefinition(proxyAddressesDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_PROXY_ADDRESSES_NAME), - PrimitiveType.XSD_STRING, 0, -1); - assertTrue("proxyAddressesDef read", proxyAddressesDef.canRead()); - assertTrue("proxyAddressesDef modify", proxyAddressesDef.canModify()); - assertTrue("proxyAddressesDef add", proxyAddressesDef.canAdd()); - // TODO: proxyAddressesDef.getMatchingRuleQName() - - return accountObjectClassDefinition; - } - - default void assertExchangeSchema(PrismObject resource, QName accountObjectClassQName, PrismContext prismContext) throws SchemaException { - - ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); - assertExchangeSchema(resourceSchema, accountObjectClassQName); - - RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); - assertExchangeSchema(refinedSchema, accountObjectClassQName); - } - - default void assertExchangeSchema(ResourceSchema resourceSchema, QName accountObjectClassQName) { - ObjectClassComplexTypeDefinition msExchBaseClassObjectClassDefinition = resourceSchema.findObjectClassDefinition(OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME); - assertNotNull("No definition for object class " + OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME, msExchBaseClassObjectClassDefinition); - display("Object class " + OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME + " def", msExchBaseClassObjectClassDefinition); - - ResourceAttributeDefinition msExchHideFromAddressListsDef = msExchBaseClassObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); - PrismAsserts.assertDefinition(msExchHideFromAddressListsDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME), DOMUtil.XSD_BOOLEAN, 0, 1); - assertTrue("msExchHideFromAddressLists read", msExchHideFromAddressListsDef.canRead()); - assertTrue("msExchHideFromAddressLists modify", msExchHideFromAddressListsDef.canModify()); - assertTrue("msExchHideFromAddressLists add", msExchHideFromAddressListsDef.canAdd()); - - ObjectClassComplexTypeDefinition accountObjectClassDef = resourceSchema.findObjectClassDefinition(accountObjectClassQName); - assertNotNull("No definition for object class " + accountObjectClassQName, accountObjectClassDef); - display("Object class " + accountObjectClassQName + " def", accountObjectClassDef); - - ResourceAttributeDefinition accountMsExchHideFromAddressListsDef = accountObjectClassDef.findAttributeDefinition(ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); - PrismAsserts.assertDefinition(accountMsExchHideFromAddressListsDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME), DOMUtil.XSD_BOOLEAN, 0, 1); - assertTrue("msExchHideFromAddressLists read", accountMsExchHideFromAddressListsDef.canRead()); - assertTrue("msExchHideFromAddressLists modify", accountMsExchHideFromAddressListsDef.canModify()); - assertTrue("msExchHideFromAddressLists add", accountMsExchHideFromAddressListsDef.canAdd()); - } - - default long getWin32Filetime(long millis) { - return (millis + 11644473600000L) * 10000L; - } - - default void display(String title, DebugDumpable value) { - PrismTestUtil.display(title, value); - } - - default void display(String title, Object value) { - PrismTestUtil.display(title, value); - } -} +/* + * Copyright (c) 2016 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.testing.conntest.ad; + +import static org.testng.AssertJUnit.*; + +import javax.xml.namespace.QName; + +import com.evolveum.midpoint.common.refinery.RefinedResourceSchema; +import com.evolveum.midpoint.common.refinery.RefinedResourceSchemaImpl; +import com.evolveum.midpoint.prism.PrimitiveType; +import com.evolveum.midpoint.prism.PrismContext; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.util.PrismAsserts; +import com.evolveum.midpoint.prism.util.PrismTestUtil; +import com.evolveum.midpoint.schema.constants.MidPointConstants; +import com.evolveum.midpoint.schema.processor.ObjectClassComplexTypeDefinition; +import com.evolveum.midpoint.schema.processor.ResourceAttributeDefinition; +import com.evolveum.midpoint.schema.processor.ResourceSchema; +import com.evolveum.midpoint.schema.util.ResourceTypeUtil; +import com.evolveum.midpoint.tools.testng.MidpointTestMixin; +import com.evolveum.midpoint.util.DOMUtil; +import com.evolveum.midpoint.util.DebugDumpable; +import com.evolveum.midpoint.util.exception.SchemaException; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; + +/** + * Mixin providing common methods/utilities for Active Directory (AD) related tests. + */ +public interface AdTestMixin extends MidpointTestMixin { + + String ATTRIBUTE_OBJECT_GUID_NAME = "objectGUID"; + String ATTRIBUTE_OBJECT_SID_NAME = "objectSid"; + String ATTRIBUTE_OBJECT_CATEGORY_NAME = "objectCategory"; + String ATTRIBUTE_SAM_ACCOUNT_NAME_NAME = "sAMAccountName"; + String ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME = "userAccountControl"; + QName ATTRIBUTE_USER_ACCOUNT_CONTROL_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_USER_ACCOUNT_CONTROL_NAME); + String ATTRIBUTE_UNICODE_PWD_NAME = "unicodePwd"; + String ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME = "msExchHideFromAddressLists"; + QName ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_QNAME = new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); + String ATTRIBUTE_TITLE_NAME = "title"; + String ATTRIBUTE_PROXY_ADDRESSES_NAME = "proxyAddresses"; + String ATTRIBUTE_USER_PARAMETERS_NAME = "userParameters"; + + QName OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME = new QName(MidPointConstants.NS_RI, "msExchBaseClass"); + + String AD_CONNECTOR_TYPE = "com.evolveum.polygon.connector.ldap.ad.AdLdapConnector"; + + /** + * Returns dashed GUID notation formatted from simple hex-encoded binary. + *

+ * E.g. "2f01c06bb1d0414e9a69dd3841a13506" -> "6bc0012f-d0b1-4e41-9a69-dd3841a13506" + */ + default String formatGuidToDashedNotation(String hexValue) { + if (hexValue == null) { + return null; + } + return hexValue.substring(6, 8) + + hexValue.substring(4, 6) + + hexValue.substring(2, 4) + + hexValue.substring(0, 2) + + '-' + + hexValue.substring(10, 12) + + hexValue.substring(8, 10) + + '-' + + hexValue.substring(14, 16) + + hexValue.substring(12, 14) + + '-' + + hexValue.substring(16, 20) + + '-' + + hexValue.substring(20, 32); + } + + default ObjectClassComplexTypeDefinition assertAdResourceSchema( + PrismObject resource, QName accountObjectClass, PrismContext prismContext) + throws SchemaException { + ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); + display("Resource schema", resourceSchema); + ResourceTypeUtil.validateSchema(resourceSchema, resource); + return assertAdSchema(resource, accountObjectClass); + } + + default ObjectClassComplexTypeDefinition assertAdResourceSchemaLongTimestamp( + PrismObject resource, QName accountObjectClass, PrismContext prismContext) + throws SchemaException { + ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); + display("Resource schema", resourceSchema); + ResourceTypeUtil.validateSchema(resourceSchema, resource); + return assertAdSchemaLongTimestamp(resource, accountObjectClass); + } + + default ObjectClassComplexTypeDefinition assertAdRefinedSchema( + PrismObject resource, QName accountObjectClass) throws SchemaException { + RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); + display("Refined schema", refinedSchema); + RefinedResourceSchemaImpl.validateRefinedSchema(refinedSchema, resource); + return assertAdSchema(resource, accountObjectClass); + } + + // Assumes string timestamp + default ObjectClassComplexTypeDefinition assertAdSchema( + PrismObject resource, QName accountObjectClass) throws SchemaException { + ObjectClassComplexTypeDefinition accountObjectClassDefinition = assertAdSchemaBase(resource, accountObjectClass); + + ResourceAttributeDefinition createTimestampDef = + accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); + PrismAsserts.assertDefinition(createTimestampDef, + new QName(MidPointConstants.NS_RI, "createTimeStamp"), DOMUtil.XSD_DATETIME, 0, 1); + assertTrue("createTimeStampDef read", createTimestampDef.canRead()); + assertFalse("createTimeStampDef modify", createTimestampDef.canModify()); + assertFalse("createTimeStampDef add", createTimestampDef.canAdd()); + + ResourceAttributeDefinition whenChangedDef = + accountObjectClassDefinition.findAttributeDefinition("whenChanged"); + PrismAsserts.assertDefinition(whenChangedDef, + new QName(MidPointConstants.NS_RI, "createTimeStamp"), DOMUtil.XSD_DATETIME, 0, 1); + assertTrue("whenChanged read", whenChangedDef.canRead()); + assertFalse("whenChanged modify", whenChangedDef.canModify()); + assertFalse("whenChanged add", whenChangedDef.canAdd()); + + return accountObjectClassDefinition; + } + + // Assumes string timestamp + default ObjectClassComplexTypeDefinition assertAdSchemaLongTimestamp( + PrismObject resource, QName accountObjectClass) throws SchemaException { + ObjectClassComplexTypeDefinition accountObjectClassDefinition = assertAdSchemaBase(resource, accountObjectClass); + + ResourceAttributeDefinition createTimestampDef = accountObjectClassDefinition.findAttributeDefinition("createTimeStamp"); + PrismAsserts.assertDefinition(createTimestampDef, new QName(MidPointConstants.NS_RI, "createTimeStamp"), + DOMUtil.XSD_LONG, 0, 1); + assertTrue("createTimeStampDef read", createTimestampDef.canRead()); + assertFalse("createTimeStampDef modify", createTimestampDef.canModify()); + assertFalse("createTimeStampDef add", createTimestampDef.canAdd()); + + return accountObjectClassDefinition; + } + + // TODO after ditching JDK 8 + /*private*/ default ObjectClassComplexTypeDefinition assertAdSchemaBase( + PrismObject resource, QName accountObjectClass) throws SchemaException { + + RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); + display("Refined schema", refinedSchema); + ObjectClassComplexTypeDefinition accountObjectClassDefinition = refinedSchema.findObjectClassDefinition(accountObjectClass); + assertNotNull("No definition for object class " + accountObjectClass, accountObjectClassDefinition); + display("Account object class def", accountObjectClassDefinition); + + ResourceAttributeDefinition cnDef = accountObjectClassDefinition.findAttributeDefinition("cn"); + PrismAsserts.assertDefinition(cnDef, new QName(MidPointConstants.NS_RI, "cn"), DOMUtil.XSD_STRING, 0, 1); + assertTrue("cn read", cnDef.canRead()); + assertTrue("cn modify", cnDef.canModify()); + assertTrue("cn add", cnDef.canAdd()); + + ResourceAttributeDefinition samAccountNameDef = accountObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_SAM_ACCOUNT_NAME_NAME); + PrismAsserts.assertDefinition(samAccountNameDef, + new QName(MidPointConstants.NS_RI, ATTRIBUTE_SAM_ACCOUNT_NAME_NAME), DOMUtil.XSD_STRING, 0, 1); + assertTrue("samAccountNameDef read", samAccountNameDef.canRead()); + assertTrue("samAccountNameDef modify", samAccountNameDef.canModify()); + assertTrue("samAccountNameDef add", samAccountNameDef.canAdd()); + + ResourceAttributeDefinition oDef = accountObjectClassDefinition.findAttributeDefinition("o"); + PrismAsserts.assertDefinition(oDef, new QName(MidPointConstants.NS_RI, "o"), DOMUtil.XSD_STRING, 0, -1); + assertTrue("o read", oDef.canRead()); + assertTrue("o modify", oDef.canModify()); + assertTrue("o add", oDef.canAdd()); + + ResourceAttributeDefinition isCriticalSystemObjectDef = accountObjectClassDefinition.findAttributeDefinition("isCriticalSystemObject"); + PrismAsserts.assertDefinition(isCriticalSystemObjectDef, new QName(MidPointConstants.NS_RI, "isCriticalSystemObject"), + PrimitiveType.XSD_BOOLEAN, 0, 1); + assertTrue("isCriticalSystemObject read", isCriticalSystemObjectDef.canRead()); + assertTrue("isCriticalSystemObject modify", isCriticalSystemObjectDef.canModify()); + assertTrue("isCriticalSystemObject add", isCriticalSystemObjectDef.canAdd()); + + ResourceAttributeDefinition nTSecurityDescriptorDef = accountObjectClassDefinition.findAttributeDefinition("nTSecurityDescriptor"); + PrismAsserts.assertDefinition(nTSecurityDescriptorDef, new QName(MidPointConstants.NS_RI, "nTSecurityDescriptor"), + PrimitiveType.XSD_BASE64BINARY, 0, 1); + assertTrue("nTSecurityDescriptor read", nTSecurityDescriptorDef.canRead()); + assertTrue("nTSecurityDescriptor modify", nTSecurityDescriptorDef.canModify()); + assertTrue("nTSecurityDescriptor add", nTSecurityDescriptorDef.canAdd()); + + ResourceAttributeDefinition objectSidDef = accountObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_OBJECT_SID_NAME); + PrismAsserts.assertDefinition(objectSidDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_OBJECT_SID_NAME), + PrimitiveType.XSD_STRING, 0, 1); + assertTrue("objectSid read", objectSidDef.canRead()); + assertFalse("objectSid modify", objectSidDef.canModify()); + assertFalse("objectSid add", objectSidDef.canAdd()); + + ResourceAttributeDefinition lastLogonDef = accountObjectClassDefinition.findAttributeDefinition("lastLogon"); + PrismAsserts.assertDefinition(lastLogonDef, new QName(MidPointConstants.NS_RI, "lastLogon"), + PrimitiveType.XSD_LONG, 0, 1); + assertTrue("lastLogonDef read", lastLogonDef.canRead()); + assertTrue("lastLogonDef modify", lastLogonDef.canModify()); + assertTrue("lastLogonDef add", lastLogonDef.canAdd()); + + ResourceAttributeDefinition proxyAddressesDef = accountObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_PROXY_ADDRESSES_NAME); + PrismAsserts.assertDefinition(proxyAddressesDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_PROXY_ADDRESSES_NAME), + PrimitiveType.XSD_STRING, 0, -1); + assertTrue("proxyAddressesDef read", proxyAddressesDef.canRead()); + assertTrue("proxyAddressesDef modify", proxyAddressesDef.canModify()); + assertTrue("proxyAddressesDef add", proxyAddressesDef.canAdd()); + // TODO: proxyAddressesDef.getMatchingRuleQName() + + return accountObjectClassDefinition; + } + + default void assertExchangeSchema(PrismObject resource, QName accountObjectClassQName, PrismContext prismContext) throws SchemaException { + + ResourceSchema resourceSchema = RefinedResourceSchema.getResourceSchema(resource, prismContext); + assertExchangeSchema(resourceSchema, accountObjectClassQName); + + RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resource); + assertExchangeSchema(refinedSchema, accountObjectClassQName); + } + + default void assertExchangeSchema(ResourceSchema resourceSchema, QName accountObjectClassQName) { + ObjectClassComplexTypeDefinition msExchBaseClassObjectClassDefinition = resourceSchema.findObjectClassDefinition(OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME); + assertNotNull("No definition for object class " + OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME, msExchBaseClassObjectClassDefinition); + display("Object class " + OBJECT_CLASS_MS_EXCH_BASE_CLASS_QNAME + " def", msExchBaseClassObjectClassDefinition); + + ResourceAttributeDefinition msExchHideFromAddressListsDef = msExchBaseClassObjectClassDefinition.findAttributeDefinition(ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); + PrismAsserts.assertDefinition(msExchHideFromAddressListsDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME), DOMUtil.XSD_BOOLEAN, 0, 1); + assertTrue("msExchHideFromAddressLists read", msExchHideFromAddressListsDef.canRead()); + assertTrue("msExchHideFromAddressLists modify", msExchHideFromAddressListsDef.canModify()); + assertTrue("msExchHideFromAddressLists add", msExchHideFromAddressListsDef.canAdd()); + + ObjectClassComplexTypeDefinition accountObjectClassDef = resourceSchema.findObjectClassDefinition(accountObjectClassQName); + assertNotNull("No definition for object class " + accountObjectClassQName, accountObjectClassDef); + display("Object class " + accountObjectClassQName + " def", accountObjectClassDef); + + ResourceAttributeDefinition accountMsExchHideFromAddressListsDef = accountObjectClassDef.findAttributeDefinition(ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME); + PrismAsserts.assertDefinition(accountMsExchHideFromAddressListsDef, new QName(MidPointConstants.NS_RI, ATTRIBUTE_MS_EXCH_HIDE_FROM_ADDRESS_LISTS_NAME), DOMUtil.XSD_BOOLEAN, 0, 1); + assertTrue("msExchHideFromAddressLists read", accountMsExchHideFromAddressListsDef.canRead()); + assertTrue("msExchHideFromAddressLists modify", accountMsExchHideFromAddressListsDef.canModify()); + assertTrue("msExchHideFromAddressLists add", accountMsExchHideFromAddressListsDef.canAdd()); + } + + default long getWin32Filetime(long millis) { + return (millis + 11644473600000L) * 10000L; + } + + default void display(String title, DebugDumpable value) { + PrismTestUtil.display(title, value); + } + + default void display(String title, Object value) { + PrismTestUtil.display(title, value); + } +} From b0f92237ef520e60d2a70f56464956fbdb4eee3a Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Mon, 9 Mar 2020 21:02:05 +0100 Subject: [PATCH 40/55] Fix retrieval options support in task manager 1) getTask method now respects the retrieval options 2) searchObjects now implements subtasks retrieval Also, - TaskType.F_SUBTASK was removed (replaced by F_SUBTASK_REF) - TestQuartzTaskManagerContract was renamed to TestTaskManagerContract This fixes MID-5374 and relates to MID-2353. --- .../web/page/admin/server/PageTask.java | 2 +- .../web/page/admin/server/PageTasks.java | 2 +- .../server/TaskOperationStatisticsPanel.java | 2 +- .../page/admin/server/TaskTabsVisibility.java | 2 +- .../midpoint/schema/SelectorOptions.java | 2 +- .../midpoint/schema/util/TaskTypeUtil.java | 9 ++ .../xml/ns/public/common/common-core-3.xsd | 12 -- .../intest/sync/TestProgressReporting.java | 4 +- .../test/AbstractModelIntegrationTest.java | 4 +- .../midpoint/task/api/TaskManager.java | 4 - .../quartzimpl/TaskManagerQuartzImpl.java | 116 ++++++++--------- .../task/quartzimpl/TaskQuartzImpl.java | 2 +- .../quartzimpl/AbstractTaskManagerTest.java | 3 +- ...ract.java => TestTaskManagerContract.java} | 122 +++++++++++++----- .../task-200RetrieveSubtasks-child-1-1.xml | 18 +++ .../task-200RetrieveSubtasks-child-1.xml | 19 +++ .../task-200RetrieveSubtasks-child-2.xml | 18 +++ .../basic/task-200RetrieveSubtasks.xml | 18 +++ repo/task-quartz-impl/testng-integration.xml | 2 +- 19 files changed, 233 insertions(+), 128 deletions(-) rename repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/{TestQuartzTaskManagerContract.java => TestTaskManagerContract.java} (93%) create mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1-1.xml create mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1.xml create mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-2.xml create mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks.xml diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java index d71d2265a0c..4220cdafaef 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTask.java @@ -117,7 +117,7 @@ protected Collection> buildGetOptions() { return getOperationOptionsBuilder() // retrieve - .item(TaskType.F_SUBTASK).retrieve() + .item(TaskType.F_SUBTASK_REF).retrieve() .item(TaskType.F_NODE_AS_OBSERVED).retrieve() .item(TaskType.F_NEXT_RUN_START_TIMESTAMP).retrieve() .item(TaskType.F_NEXT_RETRY_TIMESTAMP).retrieve() diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java index ab16a4fd84e..e982709a17a 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/PageTasks.java @@ -186,7 +186,7 @@ private Collection> createOperationOptions( propertiesToGet.add(TaskType.F_NODE_AS_OBSERVED); propertiesToGet.add(TaskType.F_NEXT_RUN_START_TIMESTAMP); propertiesToGet.add(TaskType.F_NEXT_RETRY_TIMESTAMP); - propertiesToGet.add(TaskType.F_SUBTASK); + propertiesToGet.add(TaskType.F_SUBTASK_REF); GetOperationOptionsBuilder getOperationOptionsBuilder = getSchemaHelper().getOperationOptionsBuilder(); getOperationOptionsBuilder = getOperationOptionsBuilder.resolveNames(); diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java index b0fc03d8c46..46aedf2685c 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskOperationStatisticsPanel.java @@ -125,7 +125,7 @@ private void resolveSubTasks(TaskType subTask, boolean alreadyLoaded, List PATHS_NOT_RETURNED_BY_DEFAULT = new HashSet<>(Arrays.asList( ItemPath.create(UserType.F_JPEG_PHOTO), ItemPath.create(TaskType.F_RESULT), - ItemPath.create(TaskType.F_SUBTASK), + ItemPath.create(TaskType.F_SUBTASK_REF), ItemPath.create(TaskType.F_NODE_AS_OBSERVED), ItemPath.create(TaskType.F_NEXT_RUN_START_TIMESTAMP), ItemPath.create(TaskType.F_NEXT_RETRY_TIMESTAMP), diff --git a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java index 43c5ab206ae..8dda21c1862 100644 --- a/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java +++ b/infra/schema/src/main/java/com/evolveum/midpoint/schema/util/TaskTypeUtil.java @@ -117,4 +117,13 @@ public static OperationStatsType getAggregatedOperationStats(TaskType task, Pris .synchronizationInformation(synchronizationInformation) .actionsExecutedInformation(actionsExecutedInformation); } + + public static TaskType findChild(TaskType parent, String childOid) { + for (TaskType subtask : getResolvedSubtasks(parent)) { + if (childOid.equals(subtask.getOid())) { + return subtask; + } + } + return null; + } } diff --git a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd index 4fa8bbb8464..94583db492f 100755 --- a/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd +++ b/infra/schema/src/main/resources/xml/ns/public/common/common-core-3.xsd @@ -2617,18 +2617,6 @@ - - - - Set of task's subtasks. - TRANSIENT attribute. In the repository the parent-child relationship is stored using "parent" property. - TODO: do we still need this? - - - tns:subtaskRef - - - diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestProgressReporting.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestProgressReporting.java index 88eebcf36c7..9a343a267c4 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestProgressReporting.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestProgressReporting.java @@ -102,7 +102,7 @@ private void executeReconciliation(TestResource reconciliationTask, String accou System.out.println("Task tree suspended."); Collection> getSubtasks = getOperationOptionsBuilder() - .item(TaskType.F_SUBTASK).retrieve() + .item(TaskType.F_SUBTASK_REF).retrieve() .build(); PrismObject rootAfterSuspension1 = taskManager.getObject(TaskType.class, reconciliationTask.oid, getSubtasks, result); display("Tree after suspension", TaskDebugUtil.dumpTaskTree(rootAfterSuspension1.asObjectable())); @@ -189,7 +189,7 @@ private void executeRecomputation(TestResource recomputationTask, String rolePre System.out.println("Task tree suspended."); Collection> getSubtasks = getOperationOptionsBuilder() - .item(TaskType.F_SUBTASK).retrieve() + .item(TaskType.F_SUBTASK_REF).retrieve() .build(); PrismObject rootAfterSuspension1 = taskManager.getObject(TaskType.class, recomputationTask.oid, getSubtasks, result); display("Tree after suspension", TaskDebugUtil.dumpTaskTree(rootAfterSuspension1.asObjectable())); diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index 8684b46f894..9ee441763a8 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -3130,7 +3130,7 @@ protected void dumpTaskTree(String oid, OperationResult result) throws ObjectNotFoundException, SchemaException { Collection> options = schemaHelper.getOperationOptionsBuilder() - .item(TaskType.F_SUBTASK).retrieve() + .item(TaskType.F_SUBTASK_REF).retrieve() .build(); PrismObject task = taskManager.getObject(TaskType.class, oid, options, result); dumpTaskAndSubtasks(task.asObjectable(), 0); @@ -3822,7 +3822,7 @@ protected PrismObject getTask(String taskOid) protected PrismObject getTaskTree(String taskOid) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { Task task = createPlainTask("getTaskTree"); OperationResult result = task.getResult(); - PrismObject retTask = modelService.getObject(TaskType.class, taskOid, retrieveItemsNamed(TaskType.F_RESULT, TaskType.F_SUBTASK), task, result); + PrismObject retTask = modelService.getObject(TaskType.class, taskOid, retrieveItemsNamed(TaskType.F_RESULT, TaskType.F_SUBTASK_REF), task, result); result.computeStatus(); TestUtil.assertSuccess("getObject(Task) result not success", result); return retTask; diff --git a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java index 16e26239b43..5bed2cbab92 100644 --- a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java +++ b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java @@ -264,10 +264,6 @@ void modifyTask(String oid, Collection modifications, Opera @NotNull Task getTaskWithResult(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; - /** - * BEWARE: This method does not obey taskManager-related options, e.g. retrieve(F_SUBTASK). If you need to apply them, - * use getTaskObject instead. See MID-5374. - */ @NotNull Task getTask(String taskOid, Collection> options, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java index ba400b55882..6107b33069f 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java @@ -859,31 +859,6 @@ public TaskQuartzImpl getTaskWithResult(String taskOid, OperationResult parentRe return getTask(taskOid, options, parentResult); } - - @Override - @NotNull - public TaskQuartzImpl getTask(String taskOid, Collection> options, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { - OperationResult result = parentResult.createMinorSubresult(DOT_INTERFACE + "getTask"); // todo ... or .createSubresult (without 'minor')? - result.addParam(OperationResult.PARAM_OID, taskOid); - result.addArbitraryObjectCollectionAsParam(OperationResult.PARAM_OPTIONS, options); - result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskManagerQuartzImpl.class); - - TaskQuartzImpl task; - try { - PrismObject taskPrism = repositoryService.getObject(TaskType.class, taskOid, options, result); - task = createTaskInstance(taskPrism, result); - } catch (ObjectNotFoundException e) { - result.recordFatalError("Task not found", e); - throw e; - } catch (SchemaException e) { - result.recordFatalError("Task schema error: "+e.getMessage(), e); - throw e; - } - - result.recordSuccess(); - return task; - } - @Override public void switchToBackground(final Task task, OperationResult parentResult) { @@ -1195,7 +1170,7 @@ public void unregisterRunningTask(RunningTaskQuartzImpl task) { // registeredTransientTasks.put(task.getTaskIdentifier(), task); // } - public void startLightweightTask(final RunningTaskQuartzImpl task) { + void startLightweightTask(final RunningTaskQuartzImpl task) { if (task.isPersistent()) { throw new IllegalStateException("An attempt to start LightweightTaskHandler in a persistent task; task = " + task); } @@ -1289,9 +1264,6 @@ public void waitForTransientChildren(RunningTask task, OperationResult result) { //endregion //region Getting and searching for tasks and nodes - /* - * ********************* GETTING AND SEARCHING FOR TASKS AND NODES ********************* - */ @Override public PrismObject getObject(Class type, @@ -1312,8 +1284,9 @@ public PrismObject getObject(Class type, //noinspection unchecked return (PrismObject) repositoryService.getObject(TaskType.class, oid, options, result); } else { + Task task = getTask(oid, options, result); //noinspection unchecked - return (PrismObject) getTaskAsObject(oid, options, result); + return (PrismObject) task.getUpdatedTaskObject(); } } else if (NodeType.class.isAssignableFrom(type)) { //noinspection unchecked @@ -1326,23 +1299,39 @@ public PrismObject getObject(Class type, } } - private PrismObject getTaskAsObject(String oid, Collection> options, OperationResult result) throws SchemaException, ObjectNotFoundException { + @Override + @NotNull + public TaskQuartzImpl getTask(String oid, Collection> options, + OperationResult parentResult) throws SchemaException, ObjectNotFoundException { + OperationResult result = parentResult.createMinorSubresult(DOT_INTERFACE + "getTask"); + result.addParam(OperationResult.PARAM_OID, oid); + result.addArbitraryObjectCollectionAsParam(OperationResult.PARAM_OPTIONS, options); + result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskManagerQuartzImpl.class); + try { + ClusterStatusInformation clusterStatusInformation = getClusterStatusInformation(options, TaskType.class, + true, result); // returns null if noFetch is set - ClusterStatusInformation clusterStatusInformation = getClusterStatusInformation(options, TaskType.class, true, result); // returns null if noFetch is set + PrismObject taskPrism = repositoryService.getObject(TaskType.class, oid, options, result); + TaskQuartzImpl task = createTaskInstance(taskPrism, result); - TaskQuartzImpl task = getTask(oid, options, result); - addTransientTaskInformation(task, - clusterStatusInformation, - SelectorOptions.hasToLoadPath(TaskType.F_NEXT_RUN_START_TIMESTAMP, options), - SelectorOptions.hasToLoadPath(TaskType.F_NEXT_RETRY_TIMESTAMP, options), - SelectorOptions.hasToLoadPath(TaskType.F_NODE_AS_OBSERVED, options), - result); + addTransientTaskInformation(task, + clusterStatusInformation, + SelectorOptions.hasToLoadPath(TaskType.F_NEXT_RUN_START_TIMESTAMP, options), + SelectorOptions.hasToLoadPath(TaskType.F_NEXT_RETRY_TIMESTAMP, options), + SelectorOptions.hasToLoadPath(TaskType.F_NODE_AS_OBSERVED, options), + result); - if (SelectorOptions.hasToLoadPath(TaskType.F_SUBTASK, options)) { - fillInSubtasks(task, clusterStatusInformation, options, result); + if (SelectorOptions.hasToLoadPath(TaskType.F_SUBTASK_REF, options)) { + fillInSubtasks(task, clusterStatusInformation, options, result); + } + fillOperationExecutionState(task); + return task; + } catch (Throwable t) { + result.recordFatalError(t); + throw t; + } finally { + result.computeStatusIfUnknown(); } - fillOperationExecutionState(task); - return task.getUpdatedTaskObject(); // task is never live running } private void fillOperationExecutionState(Task task0) { @@ -1361,7 +1350,7 @@ private void fillOperationExecutionState(Task task0) { if (operationStats != null) { operationStats.setLiveInformation(true); } - task.setOperationStatsTransient(operationStats.clone()); + task.setOperationStatsTransient(operationStats); task.setProgressTransient(taskInMemory.getProgress()); OperationResult result = taskInMemory.getResult(); @@ -1464,10 +1453,8 @@ List> listPersistentSubtasksForTask(String taskIdentifier, } @Override - public SearchResultList> searchObjects(Class type, - ObjectQuery query, - Collection> options, - OperationResult parentResult) throws SchemaException { + public SearchResultList> searchObjects(Class type, ObjectQuery query, + Collection> options, OperationResult parentResult) throws SchemaException { OperationResult result = parentResult.createMinorSubresult(DOT_INTERFACE + "searchObjects"); result.addParam("objectType", type); @@ -1583,6 +1570,7 @@ private SearchResultList> searchNodes(ObjectQuery query, C return new SearchResultList<>(list); } + @SuppressWarnings("SameParameterValue") private ClusterStatusInformation getClusterStatusInformation(Collection> options, Class objectClass, boolean allowCached, OperationResult result) { boolean noFetch = GetOperationOptions.isNoFetch(SelectorOptions.findRootOptions(options)); boolean retrieveStatus; @@ -1606,7 +1594,7 @@ private ClusterStatusInformation getClusterStatusInformation(Collection> searchTasks(ObjectQuery query, Collection> options, OperationResult result) throws SchemaException { + private SearchResultList> searchTasks(ObjectQuery query, Collection> options, OperationResult result) throws SchemaException { ClusterStatusInformation clusterStatusInformation = getClusterStatusInformation(options, TaskType.class, true, result); // returns null if noFetch is set @@ -1621,11 +1609,15 @@ public SearchResultList> searchTasks(ObjectQuery query, Co boolean retrieveNextRunStartTime = SelectorOptions.hasToLoadPath(TaskType.F_NEXT_RUN_START_TIMESTAMP, options); boolean retrieveRetryTime = SelectorOptions.hasToLoadPath(TaskType.F_NEXT_RETRY_TIMESTAMP, options); boolean retrieveNodeAsObserved = SelectorOptions.hasToLoadPath(TaskType.F_NODE_AS_OBSERVED, options); + boolean loadSubtasks = SelectorOptions.hasToLoadPath(TaskType.F_SUBTASK_REF, options); List> retval = new ArrayList<>(); for (PrismObject taskInRepository : tasksInRepository) { addTransientTaskInformation(taskInRepository, clusterStatusInformation, retrieveNextRunStartTime, retrieveRetryTime, retrieveNodeAsObserved, result); + if (loadSubtasks) { + fillInSubtasks(taskInRepository, clusterStatusInformation, options, result); + } retval.add(taskInRepository); } result.computeStatus(); @@ -1910,11 +1902,11 @@ public void setNodeErrorStatus(NodeErrorStatusType nodeErrorStatus) { } @Override - public void setBeanFactory(BeanFactory beanFactory) throws BeansException { + public void setBeanFactory(@NotNull BeanFactory beanFactory) throws BeansException { this.beanFactory = beanFactory; } - public MidpointConfiguration getMidpointConfiguration() { + MidpointConfiguration getMidpointConfiguration() { return midpointConfiguration; } @@ -2072,7 +2064,7 @@ public void scheduleRunnableTaskNow(Task task, OperationResult parentResult) { executionManager.scheduleRunnableTaskNow(task, parentResult); } - public void scheduleWaitingTaskNow(Task task, OperationResult parentResult) { + private void scheduleWaitingTaskNow(Task task, OperationResult parentResult) { executionManager.scheduleWaitingTaskNow(task, parentResult); } @@ -2092,10 +2084,6 @@ public void scheduleTasksNow(Collection taskOids, OperationResult parent result.computeStatus(); } - public void unscheduleTask(Task task, OperationResult parentResult) { - executionManager.unscheduleTask(task, parentResult); - } - // use with care (e.g. w.r.t. dependent tasks) public void closeTask(Task task, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { try { @@ -2114,7 +2102,7 @@ private boolean shouldPurgeResult(Task task) { } // do not forget to kick dependent tasks when closing this one (currently only done in finishHandler) - public void closeTaskWithoutSavingState(Task task, OperationResult parentResult) { + void closeTaskWithoutSavingState(Task task, OperationResult parentResult) { try { OperationResult taskResult = updateTaskResult(task, parentResult); task.close(taskResult, false, parentResult); @@ -2194,7 +2182,7 @@ public PrismObject getTaskTypeByIdentifier(String identifier, Collecti throw new IllegalStateException("Found more than one task with identifier " + identifier + " (" + list.size() + " of them)"); } PrismObject retval = list.get(0); - if (SelectorOptions.hasToLoadPath(TaskType.F_SUBTASK, options)) { + if (SelectorOptions.hasToLoadPath(TaskType.F_SUBTASK_REF, options)) { ClusterStatusInformation clusterStatusInformation = getClusterStatusInformation(options, TaskType.class, true, result); // returns null if noFetch is set fillInSubtasks(retval.asObjectable(), clusterStatusInformation, options, result); } @@ -2207,7 +2195,6 @@ List resolveTasksFromTaskTypes(List> taskPrisms, Ope for (PrismObject taskPrism : taskPrisms) { tasks.add(createTaskInstance(taskPrism, result)); } - result.recordSuccessIfUnknown(); return tasks; } @@ -2321,7 +2308,7 @@ public void cleanupTasks(CleanupPolicyType policy, RunningTask executionTask, Op } @Override - public void cleanupNodes(DeadNodeCleanupPolicyType policy, RunningTask task, OperationResult parentResult) throws SchemaException { + public void cleanupNodes(DeadNodeCleanupPolicyType policy, RunningTask task, OperationResult parentResult) { if (policy.getMaxAge() == null) { return; } @@ -2395,8 +2382,8 @@ public Thread getTaskThread(String oid) { } public static class NextStartTimes { - final Long nextScheduledRun; - final Long nextRetry; + private final Long nextScheduledRun; + private final Long nextRetry; public NextStartTimes(Trigger standardTrigger, Trigger nextRetryTrigger) { this.nextScheduledRun = getTime(standardTrigger); this.nextRetry = getTime(nextRetryTrigger); @@ -2407,7 +2394,7 @@ private Long getTime(Trigger t) { } @NotNull - public NextStartTimes getNextStartTimes(String oid, boolean retrieveNextRunStartTime, boolean retrieveRetryTime, + private NextStartTimes getNextStartTimes(String oid, boolean retrieveNextRunStartTime, boolean retrieveRetryTime, OperationResult parentResult) { OperationResult result = parentResult.createMinorSubresult(DOT_INTERFACE + "getNextStartTimes"); result.addParam("oid", oid); @@ -2437,6 +2424,7 @@ public void checkWaitingTasks(OperationResult result) throws SchemaException { LOGGER.trace("Check waiting tasks completed; {} tasks checked.", count); } + @SuppressWarnings("SameParameterValue") private List listWaitingTasks(TaskWaitingReason reason, OperationResult result) throws SchemaException { S_AtomicFilterEntry q = prismContext.queryFor(TaskType.class); q = q.item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.WAITING).and(); @@ -2458,7 +2446,7 @@ public Map getLocallyRunningTaskInstances() { } } - public Collection getTransientSubtasks(String identifier) { + Collection getTransientSubtasks(String identifier) { List retval = new ArrayList<>(); RunningTaskQuartzImpl runningInstance = locallyRunningTaskInstancesMap.get(identifier); if (runningInstance != null) { diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskQuartzImpl.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskQuartzImpl.java index d853406cd97..0c71ffba096 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskQuartzImpl.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskQuartzImpl.java @@ -603,7 +603,7 @@ public void setOperationStats(OperationStatsType value) { } void setOperationStatsTransient(OperationStatsType value) { - setContainerableTransient(TaskType.F_OPERATION_STATS, value.clone()); + setContainerableTransient(TaskType.F_OPERATION_STATS, value != null ? value.clone() : null); } /* diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java index 04b7c23d06d..bf5778c6795 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java @@ -140,8 +140,7 @@ protected PrismObject unmarshallJaxbFromFile(String fi protected PrismObject addObjectFromFile(String filePath) throws Exception { PrismObject object = unmarshallJaxbFromFile(filePath); - System.out.println("obj: " + object.getElementName()); - OperationResult result = new OperationResult(TestQuartzTaskManagerContract.class.getName() + ".addObjectFromFile"); + OperationResult result = new OperationResult(TestTaskManagerContract.class.getName() + ".addObjectFromFile"); try { add(object, result); } catch (ObjectAlreadyExistsException e) { diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java similarity index 93% rename from repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java rename to repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java index 0654aeff1d2..667f2a4a454 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestQuartzTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java @@ -6,6 +6,8 @@ */ package com.evolveum.midpoint.task.quartzimpl; +import static com.evolveum.midpoint.util.MiscUtil.extractSingleton; + import static org.testng.AssertJUnit.*; import static com.evolveum.midpoint.task.quartzimpl.TaskTestUtil.createExtensionDelta; @@ -18,6 +20,9 @@ import java.util.List; import javax.annotation.PostConstruct; +import com.evolveum.midpoint.prism.query.ObjectQuery; +import com.evolveum.midpoint.schema.util.TaskTypeUtil; + import org.quartz.JobExecutionContext; import org.quartz.JobKey; import org.quartz.SchedulerException; @@ -57,7 +62,7 @@ @ContextConfiguration(locations = { "classpath:ctx-task-test.xml" }) @DirtiesContext(classMode = DirtiesContext.ClassMode.AFTER_CLASS) -public class TestQuartzTaskManagerContract extends AbstractTaskManagerTest { +public class TestTaskManagerContract extends AbstractTaskManagerTest { private static final String TASK_OWNER_FILENAME = "src/test/resources/basic/owner.xml"; private static final String TASK_OWNER2_FILENAME = "src/test/resources/basic/owner2.xml"; @@ -72,8 +77,12 @@ private String taskFilename() { return taskFilename(""); } + private String taskOid(String testNumber, String subId) { + return "91919191-76e0-59e2-86d6-55665566" + subId + testNumber; + } + private String taskOid(String subId) { - return "91919191-76e0-59e2-86d6-55665566" + subId + getTestNumber(); + return taskOid(getTestNumber(), subId); } private String taskOid() { @@ -1294,7 +1303,7 @@ private void checkTaskStateRepeatedly(String taskOid, OperationResult result, in long start = System.currentTimeMillis(); while (System.currentTimeMillis() < start + duration) { Collection> options = schemaHelper.getOperationOptionsBuilder() - .item(TaskType.F_SUBTASK).retrieve() + .item(TaskType.F_SUBTASK_REF).retrieve() .build(); TaskType task = taskManager.getObject(TaskType.class, taskOid, options, result).asObjectable(); OperationStatsType stats = task.getOperationStats(); @@ -1447,7 +1456,7 @@ public void test110GroupLimit() throws Exception { private TaskType getTaskType(String oid, OperationResult result) throws SchemaException, ObjectNotFoundException { Collection> options = retrieveItemsNamed( - TaskType.F_SUBTASK, + TaskType.F_SUBTASK_REF, TaskType.F_NODE_AS_OBSERVED, TaskType.F_NEXT_RUN_START_TIMESTAMP, TaskType.F_NEXT_RETRY_TIMESTAMP); @@ -1481,37 +1490,80 @@ public void test130NodeNotAllowed() throws Exception { taskManager.suspendTasks(Collections.singleton(task.getOid()), 1000L, result); } + @Test + public void test200RetrieveSubtasks() throws Exception { + final OperationResult result = createOperationResult(); + + String rootOid = addObjectFromFile(taskFilename()).getOid(); + String child1Oid = addObjectFromFile(taskFilename("-child-1")).getOid(); + String child11Oid = addObjectFromFile(taskFilename("-child-1-1")).getOid(); + String child2Oid = addObjectFromFile(taskFilename("-child-2")).getOid(); + + Collection> withChildren = schemaHelper.getOperationOptionsBuilder() + .item(TaskType.F_SUBTASK_REF).retrieve() + .build(); + + TaskType getTask_rootNoChildren = taskManager.getTask(rootOid, null, result).getUpdatedTaskObject().asObjectable(); + TaskType getTask_rootWithChildren = taskManager.getTask(rootOid, withChildren, result).getUpdatedTaskObject().asObjectable(); + assertEquals("Wrong # of children", 0, getTask_rootNoChildren.getSubtaskRef().size()); + assertTaskTree(getTask_rootWithChildren, child1Oid, child2Oid, child11Oid); + + TaskType getObject_rootNoChildren = taskManager.getObject(TaskType.class, rootOid, null, result).asObjectable(); + TaskType getObject_rootWithChildren = taskManager.getObject(TaskType.class, rootOid, withChildren, result).asObjectable(); + assertEquals("Wrong # of children", 0, getObject_rootNoChildren.getSubtaskRef().size()); + assertTaskTree(getObject_rootWithChildren, child1Oid, child2Oid, child11Oid); + + ObjectQuery query = prismContext.queryFor(TaskType.class).id(rootOid).build(); + TaskType searchObjects_rootNoChildren = extractSingleton(taskManager.searchObjects(TaskType.class, query, null, result)).asObjectable(); + TaskType searchObjects_rootWithChildren = extractSingleton(taskManager.searchObjects(TaskType.class, query, withChildren, result)).asObjectable(); + assertEquals("Wrong # of children", 0, searchObjects_rootNoChildren.getSubtaskRef().size()); + assertTaskTree(searchObjects_rootWithChildren, child1Oid, child2Oid, child11Oid); + } + + private void assertTaskTree(TaskType rootWithChildren, String child1Oid, String child2Oid, String child11Oid) { + assertEquals("Wrong # of children of root", 2, rootWithChildren.getSubtaskRef().size()); + TaskType child1 = TaskTypeUtil.findChild(rootWithChildren, child1Oid); + TaskType child2 = TaskTypeUtil.findChild(rootWithChildren, child2Oid); + assertNotNull(child1); + assertNotNull(child2); + assertEquals("Wrong # of children of child1", 1, child1.getSubtaskRef().size()); + assertEquals("Wrong # of children of child2", 0, child2.getSubtaskRef().size()); + TaskType child11 = TaskTypeUtil.findChild(child1, child11Oid); + assertNotNull(child11); + } + @Test public void test999CheckingLeftovers() throws Exception { OperationResult result = createOperationResult(); ArrayList leftovers = new ArrayList<>(); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, "1", result); - checkLeftover(leftovers, "2", result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, "a", result); - checkLeftover(leftovers, "b", result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, "a", result); - checkLeftover(leftovers, result); - checkLeftover(leftovers, result); + checkLeftover(leftovers, "test005", result); + checkLeftover(leftovers, "test006", result); + checkLeftover(leftovers, "test008", result); + checkLeftover(leftovers, "test009", result); + checkLeftover(leftovers, "test010", result); + checkLeftover(leftovers, "test011", result); + checkLeftover(leftovers, "test012", result); + checkLeftover(leftovers, "test013", result); + checkLeftover(leftovers, "test014", result); + checkLeftover(leftovers, "test015", result); + checkLeftover(leftovers, "test016", result); + checkLeftover(leftovers, "test017", result); + checkLeftover(leftovers, "test019", result); + checkLeftover(leftovers, "test021", result); + checkLeftover(leftovers, "test021", "1", result); + checkLeftover(leftovers, "test021", "2", result); + checkLeftover(leftovers, "test022", result); + checkLeftover(leftovers, "test100", result); + checkLeftover(leftovers, "test105", result); + checkLeftover(leftovers, "test108", result); + checkLeftover(leftovers, "test108", "a", result); + checkLeftover(leftovers, "test108", "b", result); + checkLeftover(leftovers, "test110", result); + checkLeftover(leftovers, "test110", "a", result); + checkLeftover(leftovers, "test120", result); + checkLeftover(leftovers, "test130", result); + checkLeftover(leftovers, "test200", result); StringBuilder message = new StringBuilder("Leftover task(s) found:"); for (String leftover : leftovers) { @@ -1521,18 +1573,18 @@ public void test999CheckingLeftovers() throws Exception { AssertJUnit.assertTrue(message.toString(), leftovers.isEmpty()); } - private void checkLeftover(ArrayList leftovers, OperationResult result) throws Exception { - checkLeftover(leftovers, "0", result); + private void checkLeftover(ArrayList leftovers, String testNumber, OperationResult result) throws Exception { + checkLeftover(leftovers, testNumber, "0", result); } - private void checkLeftover(ArrayList leftovers, String subId, OperationResult result) throws Exception { - String oid = taskOid(subId); + private void checkLeftover(ArrayList leftovers, String testNumber, String subId, OperationResult result) throws Exception { + String oid = taskOid(testNumber, subId); Task t; try { t = getTask(oid, result); } catch (ObjectNotFoundException e) { // this is OK, test probably did not start - logger.info("Check leftovers: Task " + oid + " does not exist."); + logger.info("Check leftovers: Task {} does not exist.", oid); return; } diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1-1.xml b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1-1.xml new file mode 100644 index 00000000000..c9ac9fcedbd --- /dev/null +++ b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1-1.xml @@ -0,0 +1,18 @@ + + + + + Test200 Child 1 1 + + 11000000-76e0-59e2-86d6-556655660200 + + 10000000-76e0-59e2-86d6-556655660200 + suspended + single + diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1.xml b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1.xml new file mode 100644 index 00000000000..f4bc8a86a68 --- /dev/null +++ b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-1.xml @@ -0,0 +1,19 @@ + + + + + Test200 Child 1 + + 10000000-76e0-59e2-86d6-556655660200 + + 91919191-76e0-59e2-86d6-556655660200 + waiting + other + single + diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-2.xml b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-2.xml new file mode 100644 index 00000000000..651ef3cf371 --- /dev/null +++ b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks-child-2.xml @@ -0,0 +1,18 @@ + + + + + Test200 Child 2 + + 20000000-76e0-59e2-86d6-556655660200 + + 91919191-76e0-59e2-86d6-556655660200 + suspended + single + diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks.xml b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks.xml new file mode 100644 index 00000000000..d1737f60ee1 --- /dev/null +++ b/repo/task-quartz-impl/src/test/resources/basic/task-200RetrieveSubtasks.xml @@ -0,0 +1,18 @@ + + + + + Test200 Root + + 91919191-76e0-59e2-86d6-556655660200 + + waiting + other + single + diff --git a/repo/task-quartz-impl/testng-integration.xml b/repo/task-quartz-impl/testng-integration.xml index 1816db68bef..e01703b58d4 100644 --- a/repo/task-quartz-impl/testng-integration.xml +++ b/repo/task-quartz-impl/testng-integration.xml @@ -9,7 +9,7 @@ - + From 6316193a1a5c7a2f1f762cc77c0593f668c01b39 Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Tue, 10 Mar 2020 00:23:39 +0100 Subject: [PATCH 41/55] Fix failing TestImportRecon We need to be careful when using checkSubresult parameter while waiting for task finish. --- .../evolveum/midpoint/model/intest/sync/TestImportRecon.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java index f3d33bd5f8c..d15b4f1e996 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestImportRecon.java @@ -2526,7 +2526,7 @@ public void test520ReconResourceDummyFilter() throws Exception { return null; }); - Task taskAfter = waitForTaskFinish(TASK_RECONCILE_DUMMY_FILTER.oid, true, 40000); + Task taskAfter = waitForTaskFinish(TASK_RECONCILE_DUMMY_FILTER.oid, false, 40000); dumpStatistics(taskAfter); OperationStatsType statistics = taskAfter.getStoredOperationStats(); From 9d149c312e1ea3a04a98df6e812c03127a5f21bc Mon Sep 17 00:00:00 2001 From: kate Date: Tue, 10 Mar 2020 00:43:11 +0100 Subject: [PATCH 42/55] tasks tab visibility + ui authorizations --- .../midpoint/gui/api/ComponentConstants.java | 33 +++++++++++ .../web/page/admin/server/TaskMainPanel.java | 56 +++++++++++-------- .../page/admin/server/TaskTabsVisibility.java | 7 --- 3 files changed, 67 insertions(+), 29 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/ComponentConstants.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/ComponentConstants.java index fb5de99bef6..29acee60ba2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/ComponentConstants.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/ComponentConstants.java @@ -93,4 +93,37 @@ public class ComponentConstants { public static final QName UI_CASE_TAB_OVERVIEW_APPROVAL = new QName(NS_COMPONENTS_PREFIX, "caseTabOverviewApproval"); public static final String UI_CASE_TAB_OVERVIEW_APPROVAL_URL = QNameUtil.qNameToUri(UI_CASE_TAB_OVERVIEW_APPROVAL); + public static final QName UI_TASK_TAB_BASIC = new QName(NS_COMPONENTS_PREFIX, "taskTabBasic"); + public static final String UI_TASK_TAB_BASIC_URL = QNameUtil.qNameToUri(UI_TASK_TAB_BASIC); + + public static final QName UI_TASK_TAB_SCHEDULE = new QName(NS_COMPONENTS_PREFIX, "taskTabSchedule"); + public static final String UI_TASK_TAB_SCHEDULE_URL = QNameUtil.qNameToUri(UI_TASK_TAB_SCHEDULE); + + public static final QName UI_TASK_TAB_WORK_MANAGEMENT = new QName(NS_COMPONENTS_PREFIX, "taskTabWorkManagement"); + public static final String UI_TASK_TAB_WORK_MANAGEMENT_URL = QNameUtil.qNameToUri(UI_TASK_TAB_WORK_MANAGEMENT); + + public static final QName UI_TASK_TAB_CLEANUP_POLICIES = new QName(NS_COMPONENTS_PREFIX, "taskTabCleanupPolicies"); + public static final String UI_TASK_TAB_CLEANUP_POLICIES_URL = QNameUtil.qNameToUri(UI_TASK_TAB_CLEANUP_POLICIES); + + public static final QName UI_TASK_TAB_SUBTASKS = new QName(NS_COMPONENTS_PREFIX, "taskTabSubtasks"); + public static final String UI_TASK_TAB_SUBTASKS_URL = QNameUtil.qNameToUri(UI_TASK_TAB_SUBTASKS); + + public static final QName UI_TASK_TAB_OPERATION_STATISTICS = new QName(NS_COMPONENTS_PREFIX, "taskTabOperationStatistics"); + public static final String UI_TASK_TAB_OPERATION_STATISTICS_URL = QNameUtil.qNameToUri(UI_TASK_TAB_OPERATION_STATISTICS); + + public static final QName UI_TASK_TAB_ENVIRONMENTAL_PERFORMANCE = new QName(NS_COMPONENTS_PREFIX, "taskTabEnvironmentalPerformance"); + public static final String UI_TASK_TAB_ENVIRONMENTAL_PERFORMANCE_URL = QNameUtil.qNameToUri(UI_TASK_TAB_ENVIRONMENTAL_PERFORMANCE); + + public static final QName UI_TASK_TAB_OPERATION = new QName(NS_COMPONENTS_PREFIX, "taskTabOperation"); + public static final String UI_TASK_TAB_OPERATION_URL = QNameUtil.qNameToUri(UI_TASK_TAB_OPERATION); + + public static final QName UI_TASK_TAB_INTERNAL_PERFORMANCE = new QName(NS_COMPONENTS_PREFIX, "taskTabInternalPerformance"); + public static final String UI_TASK_TAB_INTERNAL_PERFORMANCE_URL = QNameUtil.qNameToUri(UI_TASK_TAB_INTERNAL_PERFORMANCE); + + public static final QName UI_TASK_TAB_RESULT = new QName(NS_COMPONENTS_PREFIX, "taskTabResult"); + public static final String UI_TASK_TAB_RESULT_URL = QNameUtil.qNameToUri(UI_TASK_TAB_RESULT); + + public static final QName UI_TASK_TAB_ERRORS = new QName(NS_COMPONENTS_PREFIX, "taskTabErrors"); + public static final String UI_TASK_TAB_ERRORS_URL = QNameUtil.qNameToUri(UI_TASK_TAB_ERRORS); + } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java index 9f9d328c427..36961d08fb2 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskMainPanel.java @@ -6,6 +6,7 @@ */ package com.evolveum.midpoint.web.page.admin.server; +import com.evolveum.midpoint.gui.api.ComponentConstants; import com.evolveum.midpoint.gui.api.component.tabs.PanelTab; import com.evolveum.midpoint.gui.api.model.LoadableModel; import com.evolveum.midpoint.gui.api.prism.ItemStatus; @@ -24,6 +25,7 @@ import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.component.AjaxSubmitButton; import com.evolveum.midpoint.web.component.objectdetails.AbstractObjectMainPanel; +import com.evolveum.midpoint.web.component.objectdetails.AssignmentHolderTypeMainPanel; import com.evolveum.midpoint.web.component.prism.ItemVisibility; import com.evolveum.midpoint.web.component.util.VisibleEnableBehaviour; import com.evolveum.midpoint.web.model.PrismContainerWrapperModel; @@ -41,7 +43,7 @@ import java.util.ArrayList; import java.util.List; -public class TaskMainPanel extends AbstractObjectMainPanel { +public class TaskMainPanel extends AssignmentHolderTypeMainPanel { private static final transient Trace LOGGER = TraceManager.getTrace(TaskMainPanel.class); @@ -70,13 +72,13 @@ protected List createTabs(PageAdminObjectDetails parentPage) { taskTabsVisibility.computeAll((PageTask) parentPage, getObjectWrapper()); ObjectTabVisibleBehavior basicTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", (PageTask) parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_BASIC_URL, (PageTask) parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isBasicVisible(); + return super.isVisible() && taskTabsVisibility.isBasicVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.basic.title"), basicTabVisibility) { @@ -90,13 +92,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior scheduleTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_SCHEDULE_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isSchedulingVisible(); + return super.isVisible() && taskTabsVisibility.isSchedulingVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.schedule.title"), scheduleTabVisibility) { @@ -110,13 +112,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior workManagementTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_CASE_TAB_WORKITEMS_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isWorkManagementVisible(); + return super.isVisible() && taskTabsVisibility.isWorkManagementVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.workManagement.title"), workManagementTabVisibility) { @@ -130,13 +132,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior cleanupPoliciesTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_CLEANUP_POLICIES_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isCleanupPolicyVisible(); + return super.isVisible() && taskTabsVisibility.isCleanupPolicyVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.cleanupPolicies.title"), cleanupPoliciesTabVisibility) { @@ -150,13 +152,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior subtasksTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_SUBTASKS_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isSubtasksAndThreadsVisible(); + return super.isVisible() && taskTabsVisibility.isSubtasksAndThreadsVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.subtasks.title"), subtasksTabVisibility) { @@ -170,13 +172,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior operationStatsAndInternalPerfTabsVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_OPERATION_STATISTICS_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isInternalPerformanceVisible(); + return super.isVisible() && taskTabsVisibility.isInternalPerformanceVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.operationStats.title"), operationStatsAndInternalPerfTabsVisibility) { @@ -190,13 +192,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior envPerfTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_ENVIRONMENTAL_PERFORMANCE_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isEnvironmentalPerformanceVisible(); + return super.isVisible() && taskTabsVisibility.isEnvironmentalPerformanceVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.environmentalPerformance.title"), envPerfTabVisibility) { @@ -210,13 +212,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior operationTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_OPERATION_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isOperationVisible(); + return super.isVisible() && taskTabsVisibility.isOperationVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTaskEdit.operation"), operationTabVisibility) { @@ -228,7 +230,17 @@ public WebMarkupContainer createPanel(String panelId) { } }); - tabs.add(new PanelTab(parentPage.createStringResource("pageTask.internalPerformance.title"), operationStatsAndInternalPerfTabsVisibility) { + ObjectTabVisibleBehavior internalPerfTabsVisibility = new ObjectTabVisibleBehavior + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_INTERNAL_PERFORMANCE_URL, parentPage){ + + private static final long serialVersionUID = 1L; + + @Override + public boolean isVisible(){ + return super.isVisible() && taskTabsVisibility.isInternalPerformanceVisible(); + } + }; + tabs.add(new PanelTab(parentPage.createStringResource("pageTask.internalPerformance.title"), internalPerfTabsVisibility) { private static final long serialVersionUID = 1L; @Override @@ -238,13 +250,13 @@ public WebMarkupContainer createPanel(String panelId) { }); ObjectTabVisibleBehavior resultTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_RESULT_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isResultVisible(); + return super.isVisible() && taskTabsVisibility.isResultVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.result.title"), resultTabVisibility) { @@ -258,13 +270,13 @@ public WebMarkupContainer createPanel(String panelId) { ObjectTabVisibleBehavior errorsTabVisibility = new ObjectTabVisibleBehavior - (Model.of(getObjectWrapper().getObject()), "", parentPage){ + (Model.of(getObjectWrapper().getObject()), ComponentConstants.UI_TASK_TAB_ERRORS_URL, parentPage){ private static final long serialVersionUID = 1L; @Override public boolean isVisible(){ - return taskTabsVisibility.isErrorsVisible(); + return super.isVisible() && taskTabsVisibility.isErrorsVisible(); } }; tabs.add(new PanelTab(parentPage.createStringResource("pageTask.errors.title"), errorsTabVisibility) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java index dbcb2242ac4..aa55f9b6a81 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/server/TaskTabsVisibility.java @@ -89,18 +89,11 @@ public boolean configuresWorkerThreads(TaskType task) { public boolean computeEnvironmentalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { final OperationStatsType operationStats = taskWrapper.getObject().asObjectable().getOperationStats(); environmentalPerformanceVisible = parentPage.isEditingFocus(); - //todo does it make sense to check operationStats? it may be null for partitioned task -// && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) -// && operationStats != null -// && !StatisticsUtil.isEmpty(operationStats.getEnvironmentalPerformanceInformation()); return environmentalPerformanceVisible; } public boolean computeInternalPerformanceVisible(PageTask parentPage, PrismObjectWrapper taskWrapper) { internalPerformanceVisible = parentPage.isEditingFocus(); - //todo doea it make sense to check operationStats? it may be null for partitioned task -// && isTaskItemReadable(taskWrapper, TaskType.F_OPERATION_STATS) -// && taskWrapper.getObject().asObjectable().getOperationStats() != null; return internalPerformanceVisible; } From 154a42c3e0aac662cef441d290dc7da76d9773a7 Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Tue, 10 Mar 2020 00:49:28 +0100 Subject: [PATCH 43/55] Revert getTask in tests to the "plain" version This commit removes all the special treatment of Quartz and live information to task in getTask method, renaming it to getTaskPlain. (This might not be the definite name, though.) This should fix recent test failures. --- .../page/admin/configuration/PageAbout.java | 2 +- .../model/impl/TestRefinedSchema.java | 12 +- .../midpoint/model/intest/sync/TestUuid.java | 6 +- .../TestValidityRecomputeTaskPartitioned.java | 2 +- .../test/AbstractModelIntegrationTest.java | 2 +- .../evolveum/midpoint/report/TestReport.java | 6 +- .../impl/opendj/TestSynchronization.java | 6 +- .../test/AbstractIntegrationTest.java | 4 +- .../midpoint/task/api/TaskManager.java | 17 ++- .../quartzimpl/TaskManagerQuartzImpl.java | 54 ++++--- .../execution/ExecutionManager.java | 4 +- .../quartzimpl/execution/JobExecutor.java | 6 +- .../execution/LocalNodeManager.java | 2 +- .../execution/StalledTasksWatcher.java | 2 +- .../execution/TaskSynchronizer.java | 2 +- .../handlers/PartitioningTaskHandler.java | 2 +- .../quartzimpl/work/WorkStateManager.java | 6 +- .../work/workers/WorkersManager.java | 4 +- .../quartzimpl/AbstractTaskManagerTest.java | 2 +- .../task/quartzimpl/TestPartitioning.java | 4 +- .../quartzimpl/TestTaskManagerContract.java | 61 ++++---- .../quartzimpl/TestWorkBucketStrategies.java | 30 ++-- .../task/quartzimpl/TestWorkDistribution.java | 142 +++++++++--------- .../quartzimpl/TestWorkersManagement.java | 32 ++-- .../testing/conntest/TestOpenLdap.java | 4 +- .../conntest/ad/AbstractAdLdapTest.java | 3 +- .../midpoint/testing/sanity/TestSanity.java | 31 ++-- .../midpoint/testing/story/TestStrings.java | 2 +- 28 files changed, 235 insertions(+), 215 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAbout.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAbout.java index 88c4ac746c9..18067b6f12f 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAbout.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/configuration/PageAbout.java @@ -514,7 +514,7 @@ private void resetStateToInitialConfig(AjaxRequestTarget target) { final String taskOidToRemoving = taskOid; try { - while(!getTaskManager().getTask(taskOid, result).isClosed()) {TimeUnit.SECONDS.sleep(5);} + while(!getTaskManager().getTaskPlain(taskOid, result).isClosed()) {TimeUnit.SECONDS.sleep(5);} runPrivileged(new Producer() { diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java index 2c491503749..8b1db12081a 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java @@ -119,7 +119,7 @@ public void test110DetermineObjectClassObjectClass() throws Exception { importObjectFromFile(TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE); - Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_OBJECTCLASS_OID, result); + Task task = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_OBJECTCLASS_OID, result); display("Task", task); // WHEN @@ -139,7 +139,7 @@ public void test112DetermineObjectClassKindIntent() throws Exception { importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_FILE); - Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OID, result); + Task task = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_KIND_INTENT_OID, result); display("Task", task); // WHEN @@ -159,7 +159,7 @@ public void test114DetermineObjectClassKindIntentObjectClass() throws Exception importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE); - Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID, result); + Task task = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID, result); display("Task", task); // WHEN @@ -179,7 +179,7 @@ public void test120DetermineObjectClassObjectClassModel() throws Exception { importObjectFromFile(TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE); - Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_OBJECTCLASS_OID, result); + Task task = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_OBJECTCLASS_OID, result); display("Task", task); // WHEN @@ -200,7 +200,7 @@ public void test122DetermineObjectClassKindIntentModel() throws Exception { importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_FILE); - Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OID, result); + Task task = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_KIND_INTENT_OID, result); display("Task", task); // WHEN @@ -222,7 +222,7 @@ public void test124DetermineObjectClassKindIntentObjectClassModel() throws Excep importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE); - Task task = taskManager.getTask(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID, result); + Task task = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_OID, result); display("Task", task); // WHEN diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java index 325e35d02c7..0e3dd4948cb 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestUuid.java @@ -159,7 +159,7 @@ public void test210ReconcileDummyUuidAddAugustus() throws Exception { rememberCounter(InternalCounters.SHADOW_FETCH_OPERATION_COUNT); reconciliationTaskResultListener.clear(); - Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); + Task taskBefore = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_UUID_OID, result); // WHEN when(); @@ -233,7 +233,7 @@ public void test220ReconcileDummyUuidDeleteAddAugustus() throws Exception { display("Old shadow OID", augustusShadowOid); display("Account ID " + oldAccount.getId() + " -> " + newAccount.getId()); - Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); + Task taskBefore = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_UUID_OID, result); getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); @@ -318,7 +318,7 @@ public void test230ReconcileDummyUuidDeleteAugustusAddAugustina() throws Excepti display("Old shadow OID", augustusShadowOid); display("Account ID " + oldAccount.getId() + " -> " + account.getId()); - Task taskBefore = taskManager.getTask(TASK_RECONCILE_DUMMY_UUID_OID, result); + Task taskBefore = taskManager.getTaskPlain(TASK_RECONCILE_DUMMY_UUID_OID, result); getDummyResource().purgeScriptHistory(); dummyAuditService.clear(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java index b6ae6ac864c..902b7e00f49 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTaskPartitioned.java @@ -40,7 +40,7 @@ protected void assertLastScanTimestamp(String taskOid, XMLGregorianCalendar star throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { OperationResult result = createOperationResult("assertLastScanTimestamp"); - Task master = taskManager.getTask(taskOid, result); + Task master = taskManager.getTaskPlain(taskOid, result); for (Task subtask : master.listSubtasks(result)) { super.assertLastScanTimestamp(subtask.getOid(), startCal, endCal); } diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index 9ee441763a8..cc2f5bfca17 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -3672,7 +3672,7 @@ protected void rerunTask(String taskOid) throws CommonException { protected void assertTaskExecutionStatus(String taskOid, TaskExecutionStatus expectedExecutionStatus) throws ObjectNotFoundException, SchemaException { final OperationResult result = new OperationResult(AbstractIntegrationTest.class + ".assertTaskExecutionStatus"); - Task task = taskManager.getTask(taskOid, result); + Task task = taskManager.getTaskPlain(taskOid, result); assertEquals("Wrong executionStatus in " + task, expectedExecutionStatus, task.getExecutionStatus()); } diff --git a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java index ff91897d09b..48a8b32f902 100644 --- a/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java +++ b/model/report-impl/src/test/java/com/evolveum/midpoint/report/TestReport.java @@ -80,7 +80,7 @@ public void test100ReportUserList() throws Exception { display("Background task", task); - waitForTaskFinish(task.getOid(), true); + waitForTaskFinish(task.getOid(), false); // THEN then(); @@ -139,7 +139,7 @@ public void test200ReportUserListScript() throws Exception { display("Background task", task); - waitForTaskFinish(task.getOid(), true); + waitForTaskFinish(task.getOid(), false); // THEN then(); @@ -198,7 +198,7 @@ protected PrismObject runReport(PrismObject report, boolea display("Background task (running)", task); - waitForTaskFinish(task.getOid(), true, DEFAULT_TASK_WAIT_TIMEOUT, errorOk); + waitForTaskFinish(task.getOid(), false, DEFAULT_TASK_WAIT_TIMEOUT, errorOk); // THEN then(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java index 5096c6a2556..39a0f704c4a 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestSynchronization.java @@ -119,7 +119,7 @@ public void test010Sanity() throws Exception { assertNotNull("No resource schema", resource.asObjectable().getSchema()); assertNotNull("No native capabilities", resource.asObjectable().getCapabilities().getNative()); - Task syncTask = taskManager.getTask(SYNC_TASK_OID, result); + Task syncTask = taskManager.getTaskPlain(SYNC_TASK_OID, result); AssertJUnit.assertNotNull(syncTask); assertSyncToken(syncTask, 0, result); } @@ -128,7 +128,7 @@ public void test010Sanity() throws Exception { public void test100SyncAddWill() throws Exception { final OperationResult result = createOperationResult(); - Task syncTask = taskManager.getTask(SYNC_TASK_OID, result); + Task syncTask = taskManager.getTaskPlain(SYNC_TASK_OID, result); AssertJUnit.assertNotNull(syncTask); assertSyncToken(syncTask, 0, result); ((SynchronizationServiceMock) syncServiceMock).reset(); @@ -187,7 +187,7 @@ public void test100SyncAddWill() throws Exception { public void test500SyncAddProtected() throws Exception { final OperationResult result = createOperationResult(); - Task syncTask = taskManager.getTask(SYNC_TASK_OID, result); + Task syncTask = taskManager.getTaskPlain(SYNC_TASK_OID, result); AssertJUnit.assertNotNull(syncTask); assertSyncToken(syncTask, 1, result); ((SynchronizationServiceMock) syncServiceMock).reset(); diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index e7bcc01508a..0027d2f82a7 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -1402,14 +1402,14 @@ protected void assertFilter(ObjectFilter filter, Class e protected void assertSyncToken(String syncTaskOid, Object expectedValue) throws ObjectNotFoundException, SchemaException { OperationResult result = new OperationResult(AbstractIntegrationTest.class.getName() + ".assertSyncToken"); - Task task = taskManager.getTask(syncTaskOid, result); + Task task = taskManager.getTaskPlain(syncTaskOid, result); assertSyncToken(task, expectedValue, result); result.computeStatus(); TestUtil.assertSuccess(result); } protected void assertSyncToken(String syncTaskOid, Object expectedValue, OperationResult result) throws ObjectNotFoundException, SchemaException { - Task task = taskManager.getTask(syncTaskOid, result); + Task task = taskManager.getTaskPlain(syncTaskOid, result); assertSyncToken(task, expectedValue, result); } diff --git a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java index 5bed2cbab92..0c8d13bae58 100644 --- a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java +++ b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/TaskManager.java @@ -253,19 +253,30 @@ void modifyTask(String oid, Collection modifications, Opera * * Works only on persistent tasks. * + * Gets the task simply by fetching it from repository. No attempts to augment it with the live data nor Quartz scheduling + * information nor subtasks is done. TODO can we use options (noFetch? raw?) to achieve this? + * * @param taskOid OID of the persistent task. * @return Task instance * @throws SchemaException error dealing with resource schema * @throws ObjectNotFoundException wrong OID format, etc. */ @NotNull - Task getTask(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; + Task getTaskPlain(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; + /** + * Gets the task simply by fetching it from repository. No attempts to augment it with the live data nor Quartz scheduling + * information nor subtasks is done. TODO can we use options (noFetch? raw?) to achieve this? + */ @NotNull - Task getTaskWithResult(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; + Task getTaskPlain(String taskOid, Collection> options, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; + /** + * Gets the task (as in getTaskPlain) but with its operation result. + */ @NotNull - Task getTask(String taskOid, Collection> options, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; + Task getTaskWithResult(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException; + /** * Returns a task with a given identifier. diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java index 6107b33069f..898bbcb51f0 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/TaskManagerQuartzImpl.java @@ -393,7 +393,7 @@ public boolean getServiceThreadsActivationState() { @Override public boolean suspendTask(String taskOid, long waitTime, OperationResult parentResult) throws SchemaException, ObjectNotFoundException { - return suspendTask(getTask(taskOid, parentResult), waitTime, parentResult); + return suspendTask(getTaskPlain(taskOid, parentResult), waitTime, parentResult); } @Override @@ -426,7 +426,7 @@ public boolean suspendTaskTree(String rootTaskOid, long waitTime, OperationResul result.addParam("waitTime", waitTime); try { - TaskQuartzImpl root = getTask(rootTaskOid, result); + TaskQuartzImpl root = getTaskPlain(rootTaskOid, result); List subtasks = root.listSubtasksDeeply(true, parentResult); List oidsToSuspend = new ArrayList<>(subtasks.size() + 1); oidsToSuspend.add(rootTaskOid); @@ -448,7 +448,7 @@ public void resumeTaskTree(String rootTaskOid, OperationResult parentResult) thr result.addParam("rootTaskOid", rootTaskOid); try { - TaskQuartzImpl root = getTask(rootTaskOid, result); + TaskQuartzImpl root = getTaskPlain(rootTaskOid, result); List subtasks = root.listSubtasksDeeply(true, parentResult); List oidsToResume = new ArrayList<>(subtasks.size() + 1); if (root.getExecutionStatus() == TaskExecutionStatus.SUSPENDED) { @@ -507,7 +507,7 @@ public void scheduleCoordinatorAndWorkersNow(String coordinatorOid, OperationRes OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "scheduleCoordinatorAndWorkersNow"); result.addParam("coordinatorOid", coordinatorOid); try { - TaskQuartzImpl coordinatorTask = getTask(coordinatorOid, result); + TaskQuartzImpl coordinatorTask = getTaskPlain(coordinatorOid, result); TaskExecutionStatus status = coordinatorTask.getExecutionStatus(); switch (status) { case CLOSED: @@ -726,7 +726,7 @@ public void resumeTasks(Collection taskOids, OperationResult parentResul OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "resumeTasks"); for (String oid : taskOids) { try { - resumeTask(getTask(oid, result), result); + resumeTask(getTaskPlain(oid, result), result); } catch (ObjectNotFoundException e) { // result is already updated LoggingUtils.logException(LOGGER, "Couldn't resume task with OID {}", e, oid); } catch (SchemaException | RuntimeException e) { @@ -738,7 +738,7 @@ public void resumeTasks(Collection taskOids, OperationResult parentResul @Override public void resumeTask(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { - resumeTask(getTask(taskOid, parentResult), parentResult); + resumeTask(getTaskPlain(taskOid, parentResult), parentResult); } @Override @@ -846,8 +846,8 @@ public TaskQuartzImpl createTaskInstance(PrismObject taskPrism, String @Override @NotNull - public TaskQuartzImpl getTask(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { - return getTask(taskOid, null, parentResult); + public TaskQuartzImpl getTaskPlain(String taskOid, OperationResult parentResult) throws ObjectNotFoundException, SchemaException { + return getTaskPlain(taskOid, null, parentResult); } @Override @@ -856,7 +856,7 @@ public TaskQuartzImpl getTaskWithResult(String taskOid, OperationResult parentRe Collection> options = schemaHelper.getOperationOptionsBuilder() .item(TaskType.F_RESULT).retrieve() .build(); - return getTask(taskOid, options, parentResult); + return getTaskPlain(taskOid, options, parentResult); } @Override @@ -991,7 +991,7 @@ public void modifyTask(String oid, Collection modifications OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "modifyTask"); try { repositoryService.modifyObject(TaskType.class, oid, modifications, result); - TaskQuartzImpl task = getTask(oid, result); + TaskQuartzImpl task = getTaskPlain(oid, result); task.setRecreateQuartzTrigger(true); synchronizeTaskWithQuartz(task, result); } finally { @@ -1008,7 +1008,7 @@ public void suspendAndDeleteTasks(Collection taskOids, long suspendTimeo List tasksToBeDeleted = new ArrayList<>(); for (String oid : taskOids) { try { - Task task = getTask(oid, result); + Task task = getTaskPlain(oid, result); tasksToBeDeleted.add(task); if (alsoSubtasks) { tasksToBeDeleted.addAll(task.listSubtasksDeeply(true, result)); @@ -1061,7 +1061,7 @@ public void suspendAndDeleteTask(String taskOid, long suspendTimeout, boolean al result.addParam("taskOid", taskOid); List tasksToBeDeleted = new ArrayList<>(); - Task thisTask = getTask(taskOid, result); + Task thisTask = getTaskPlain(taskOid, result); tasksToBeDeleted.add(thisTask); if (alsoSubtasks) { tasksToBeDeleted.addAll(thisTask.listSubtasksDeeply(true, result)); @@ -1116,7 +1116,7 @@ public void deleteTask(String oid, OperationResult parentResult) throws ObjectNo OperationResult result = parentResult.createSubresult(DOT_INTERFACE + "deleteTask"); result.addParam("oid", oid); try { - Task task = getTask(oid, result); + Task task = getTaskPlain(oid, result); if (task.getNode() != null) { result.recordWarning("Deleting a task that seems to be currently executing on node " + task.getNode()); } @@ -1300,10 +1300,28 @@ public PrismObject getObject(Class type, } @Override + @NotNull + public TaskQuartzImpl getTaskPlain(String oid, Collection> options, + OperationResult parentResult) throws SchemaException, ObjectNotFoundException { + OperationResult result = parentResult.createMinorSubresult(DOT_IMPL_CLASS + "getTaskPlain"); + result.addParam(OperationResult.PARAM_OID, oid); + result.addArbitraryObjectCollectionAsParam(OperationResult.PARAM_OPTIONS, options); + result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskManagerQuartzImpl.class); + try { + PrismObject taskPrism = repositoryService.getObject(TaskType.class, oid, options, result); + return createTaskInstance(taskPrism, result); + } catch (Throwable t) { + result.recordFatalError(t); + throw t; + } finally { + result.computeStatusIfUnknown(); + } + } + @NotNull public TaskQuartzImpl getTask(String oid, Collection> options, OperationResult parentResult) throws SchemaException, ObjectNotFoundException { - OperationResult result = parentResult.createMinorSubresult(DOT_INTERFACE + "getTask"); + OperationResult result = parentResult.createMinorSubresult(DOT_IMPL_CLASS + "getTask"); result.addParam(OperationResult.PARAM_OID, oid); result.addArbitraryObjectCollectionAsParam(OperationResult.PARAM_OPTIONS, options); result.addContext(OperationResult.CONTEXT_IMPLEMENTATION_CLASS, TaskManagerQuartzImpl.class); @@ -1766,7 +1784,7 @@ public void onTaskCreate(String oid, OperationResult parentResult) { TaskQuartzImpl task; try { - task = getTask(oid, result); + task = getTaskPlain(oid, result); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Quartz shadow job cannot be created, because task in repository was not found; oid = {}", e, oid); result.computeStatus(); @@ -2028,7 +2046,7 @@ public void deleteNode(String nodeOid, OperationResult result) throws SchemaExce @Override public void scheduleTaskNow(String taskOid, OperationResult parentResult) throws SchemaException, ObjectNotFoundException { - scheduleTaskNow(getTask(taskOid, parentResult), parentResult); + scheduleTaskNow(getTaskPlain(taskOid, parentResult), parentResult); } @Override @@ -2074,7 +2092,7 @@ public void scheduleTasksNow(Collection taskOids, OperationResult parent result.addArbitraryObjectCollectionAsParam("taskOids", taskOids); for (String oid : taskOids) { try { - scheduleTaskNow(getTask(oid, result), result); + scheduleTaskNow(getTaskPlain(oid, result), result); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Couldn't schedule task with OID {}", e, oid); } catch (SchemaException | RuntimeException e) { @@ -2357,7 +2375,7 @@ private List resolveTaskOids(Collection oids, OperationResult pare OperationResult result = parentResult.createMinorSubresult(DOT_IMPL_CLASS + ".resolveTaskOids"); for (String oid : oids) { try { - retval.add(getTask(oid, result)); + retval.add(getTaskPlain(oid, result)); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Couldn't retrieve task with OID {}", e, oid); // result is updated in getTask } catch (SchemaException e) { diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/ExecutionManager.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/ExecutionManager.java index 2a5479b8220..32d99a8a4ab 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/ExecutionManager.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/ExecutionManager.java @@ -130,7 +130,7 @@ public boolean stopSchedulersAndTasks(Collection nodeIdentifiers, long t List tasks = new ArrayList<>(); for (ClusterStatusInformation.TaskInfo taskInfo : taskInfoList) { try { - tasks.add(taskManager.getTask(taskInfo.getOid(), result)); + tasks.add(taskManager.getTaskPlain(taskInfo.getOid(), result)); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Task {} that was about to be stopped does not exist. Ignoring it.", e, taskInfo.getOid()); } catch (SchemaException e) { @@ -832,7 +832,7 @@ public String getTaskThreadsDump(String taskOid, OperationResult parentResult) StringBuilder output = new StringBuilder(); OperationResult result = parentResult.createSubresult(ExecutionManager.DOT_CLASS + "getTaskThreadsDump"); try { - TaskQuartzImpl task = taskManager.getTask(taskOid, parentResult); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid, parentResult); RunningTask localTask = taskManager.getLocallyRunningTaskByIdentifier(task.getTaskIdentifier()); Thread rootThread = taskManager.getTaskThread(taskOid); if (localTask == null || rootThread == null) { diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/JobExecutor.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/JobExecutor.java index cd802370c0d..dc546f9754f 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/JobExecutor.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/JobExecutor.java @@ -78,9 +78,7 @@ public void execute(JobExecutionContext context) throws JobExecutionException { // get the task instance String oid = context.getJobDetail().getKey().getName(); try { - Collection> options = taskManagerImpl.getSchemaHelper().getOperationOptionsBuilder() - .item(TaskType.F_RESULT).retrieve().build(); - task = taskManagerImpl.createRunningTask(taskManagerImpl.getTask(oid, options, executionResult)); + task = taskManagerImpl.createRunningTask(taskManagerImpl.getTaskWithResult(oid, executionResult)); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Task with OID {} no longer exists, removing Quartz job and exiting the execution routine.", e, oid); taskManagerImpl.getExecutionManager().removeTaskFromQuartz(oid, executionResult); @@ -365,7 +363,7 @@ private Map createGroupMap(RunningTaskQuartzImpl task, Op } Task otherTask; try { - otherTask = taskManagerImpl.getTask(taskInfo.getOid(), result); + otherTask = taskManagerImpl.getTaskPlain(taskInfo.getOid(), result); } catch (ObjectNotFoundException e) { LOGGER.debug("Couldn't find running task {} when checking execution constraints: {}", taskInfo.getOid(), e.getMessage()); diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java index 768b0fc46c7..9a0ecf30dec 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/LocalNodeManager.java @@ -471,7 +471,7 @@ Collection getLocallyRunningTasks(OperationResult parentResult) { for (String oid : getLocallyRunningTasksOids(result)) { OperationResult result1 = result.createSubresult(LocalNodeManager.class.getName() + ".getLocallyRunningTask"); try { - retval.add(taskManager.getTask(oid, result1)); + retval.add(taskManager.getTaskPlain(oid, result1)); result1.recordSuccess(); } catch (ObjectNotFoundException e) { String m = "Cannot get the task with OID " + oid + " as it no longer exists"; diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/StalledTasksWatcher.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/StalledTasksWatcher.java index b3620df784d..1b58a681c98 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/StalledTasksWatcher.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/StalledTasksWatcher.java @@ -84,7 +84,7 @@ public void checkStalledTasks(OperationResult parentResult) { realProgress = heartbeatProgressInfo; } else { try { - realProgress = taskManager.getTask(task.getOid(), result).getProgress(); + realProgress = taskManager.getTaskPlain(task.getOid(), result).getProgress(); } catch (ObjectNotFoundException e) { LoggingUtils.logException(LOGGER, "Task {} cannot be checked for staleness because it is gone", e, task); continue; diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/TaskSynchronizer.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/TaskSynchronizer.java index 614d80d976d..4f0574c8b2a 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/TaskSynchronizer.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/execution/TaskSynchronizer.java @@ -109,7 +109,7 @@ boolean synchronizeJobStores(OperationResult parentResult) { oidsInRepo.add(taskPrism.getOid()); TaskQuartzImpl task; try { - task = taskManager.getTask(taskPrism.getOid(), result); // in order for the task to be "fresh" + task = taskManager.getTaskPlain(taskPrism.getOid(), result); // in order for the task to be "fresh" if (synchronizeTask(task, result)) { changed++; // todo are we sure that we increment this counter only for successfully processed tasks? we hope so :) } diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/handlers/PartitioningTaskHandler.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/handlers/PartitioningTaskHandler.java index 45e69b55d0c..4c3a33078b1 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/handlers/PartitioningTaskHandler.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/handlers/PartitioningTaskHandler.java @@ -204,7 +204,7 @@ private List createSubtasks(TaskPartitionsDefinition partitionsDefinition, } List subtasks = new ArrayList<>(subtaskOids.size()); for (String subtaskOid : subtaskOids) { - subtasks.add(taskManager.getTask(subtaskOid, opResult)); + subtasks.add(taskManager.getTaskPlain(subtaskOid, opResult)); } for (int i = 1; i <= count; i++) { Task subtask = subtasks.get(i - 1); diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/WorkStateManager.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/WorkStateManager.java index cda6ef76467..fe0e74e362c 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/WorkStateManager.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/WorkStateManager.java @@ -122,11 +122,11 @@ public boolean isStandalone() { } void reloadCoordinatorTask(OperationResult result) throws SchemaException, ObjectNotFoundException { - coordinatorTask = taskManager.getTask(coordinatorTask.getOid(), null, result); + coordinatorTask = taskManager.getTaskPlain(coordinatorTask.getOid(), null, result); } void reloadWorkerTask(OperationResult result) throws SchemaException, ObjectNotFoundException { - workerTask = taskManager.getTask(workerTask.getOid(), null, result); + workerTask = taskManager.getTaskPlain(workerTask.getOid(), null, result); } TaskWorkManagementType getWorkStateConfiguration() { @@ -495,7 +495,7 @@ private void markWorkComplete(Task task, OperationResult result) private Context createContext(String workerTaskOid, Supplier canRun, WorkBucketStatisticsCollector collector, boolean isGetOperation, OperationResult result) throws SchemaException, ObjectNotFoundException { Context ctx = new Context(canRun, collector, isGetOperation); - ctx.workerTask = taskManager.getTask(workerTaskOid, result); + ctx.workerTask = taskManager.getTaskPlain(workerTaskOid, result); TaskWorkManagementType wsConfig = ctx.workerTask.getWorkManagement(); if (wsConfig != null && wsConfig.getTaskKind() != null && wsConfig.getTaskKind() != TaskKindType.WORKER && wsConfig.getTaskKind() != TaskKindType.STANDALONE) { diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/workers/WorkersManager.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/workers/WorkersManager.java index 8e44de5550b..5c19534d947 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/workers/WorkersManager.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/work/workers/WorkersManager.java @@ -58,7 +58,7 @@ public class WorkersManager { public void reconcileWorkers(String coordinatorTaskOid, WorkersReconciliationOptions options, OperationResult result) throws SchemaException, ObjectNotFoundException, ObjectAlreadyExistsException { - Task coordinatorTask = taskManager.getTask(coordinatorTaskOid, result); + Task coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid, result); if (coordinatorTask.getKind() != TaskKindType.COORDINATOR) { throw new IllegalArgumentException("Task is not a coordinator task: " + coordinatorTask); } @@ -419,7 +419,7 @@ public void deleteWorkersAndWorkState(String rootTaskOid, boolean deleteWorkers, // TODO less harsh handling throw new IllegalStateException("Not all tasks could be suspended. Please retry to operation."); } - Task rootTask = taskManager.getTask(rootTaskOid, result); + Task rootTask = taskManager.getTaskPlain(rootTaskOid, result); deleteWorkersAndWorkState(rootTask, deleteWorkers, result); } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java index bf5778c6795..6b3545cab30 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java @@ -300,7 +300,7 @@ protected void assertOptimizedCompletedBuckets(TaskQuartzImpl task) { protected int getTotalItemsProcessed(String coordinatorTaskOid) { OperationResult result = new OperationResult("getTotalItemsProcessed"); try { - Task coordinatorTask = taskManager.getTask(coordinatorTaskOid, result); + Task coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid, result); List tasks = coordinatorTask.listSubtasks(result); int total = 0; for (Task task : tasks) { diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java index 5454d5f1cc7..473b2b3275d 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestPartitioning.java @@ -72,7 +72,7 @@ public void test100DurableRecurring() throws Exception { try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl masterTask = taskManager.getTask(masterTaskOid, result); + TaskQuartzImpl masterTask = taskManager.getTaskPlain(masterTaskOid, result); List partitions = masterTask.listSubtasks(result); display("master task", masterTask); @@ -91,7 +91,7 @@ public void test100DurableRecurring() throws Exception { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 2); waitForTaskRunnable(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL); - masterTask = taskManager.getTask(masterTaskOid, result); + masterTask = taskManager.getTaskPlain(masterTaskOid, result); partitions = masterTask.listSubtasks(result); display("master task (after 2nd run)", masterTask); display("partition tasks (after 2nd run)", partitions); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java index 667f2a4a454..9ca04d4f1ae 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java @@ -123,7 +123,7 @@ public void test003GetProgress() throws Exception { logger.trace("Retrieving the task and getting its progress..."); - TaskQuartzImpl task = getTask(taskOid(), result); + TaskQuartzImpl task = getTaskWithResult(taskOid(), result); AssertJUnit.assertEquals("Progress is not 0", 0, task.getProgress()); } @@ -146,7 +146,7 @@ public void test004aTaskBigProperty() throws Exception { addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(), result); + TaskQuartzImpl task = getTaskWithResult(taskOid(), result); // property definition ItemName bigStringQName = new ItemName("http://midpoint.evolveum.com/repo/test", "bigString"); @@ -167,7 +167,7 @@ public void test004aTaskBigProperty() throws Exception { logger.trace("Retrieving the task and comparing its properties..."); - Task task001 = getTask(taskOid(), result); + Task task001 = getTaskWithResult(taskOid(), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); PrismProperty bigString001 = task001.getExtensionPropertyOrClone(bigStringQName); @@ -184,7 +184,7 @@ public void test004aTaskBigProperty() throws Exception { System.out.println("2nd round: Task before save = " + task001.debugDump()); task001.flushPendingModifications(result); // however, this does not work, because 'modifyObject' in repo first reads object, overwriting any existing definitions ... - Task task002 = getTask(taskOid(), result); + Task task002 = getTaskWithResult(taskOid(), result); System.out.println("2nd round: Task from repo: " + task002.debugDump()); PrismProperty bigString002 = task002.getExtensionPropertyOrClone(bigStringQName); @@ -212,7 +212,7 @@ public void test004bTaskBigProperty() throws Exception { // TODO fix B file or what, so we can have this here: addObjectFromFile(taskFilename()); addObjectFromFile("src/test/resources/basic/task-004aTaskBigProperty.xml"); - TaskQuartzImpl task = getTask(taskOid(), result); + TaskQuartzImpl task = getTaskWithResult(taskOid(), result); // property definition ItemName shipStateQName = new ItemName("http://myself.me/schemas/whatever", "shipState"); @@ -229,7 +229,7 @@ public void test004bTaskBigProperty() throws Exception { logger.trace("Retrieving the task and comparing its properties..."); - Task task001 = getTask(taskOid(), result); + Task task001 = getTaskWithResult(taskOid(), result); System.out.println("1st round: Task from repo: " + task001.debugDump()); PrismProperty shipState001 = task001.getExtensionPropertyOrClone(shipStateQName); @@ -243,7 +243,7 @@ public void test004bTaskBigProperty() throws Exception { System.out.println("2nd round: Task before save = " + task001.debugDump()); task001.flushPendingModifications(result); - Task task002 = getTask(taskOid(), result); + Task task002 = getTaskWithResult(taskOid(), result); System.out.println("2nd round: Task from repo: " + task002.debugDump()); PrismProperty bigString002 = task002.getExtensionPropertyOrClone(shipStateQName); @@ -255,7 +255,7 @@ public void test004cReferenceInExtension() throws Exception { // o OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(), result); + TaskQuartzImpl task = getTaskWithResult(taskOid(), result); System.out.println("Task extension = " + task.getExtensionOrClone()); @@ -277,7 +277,7 @@ public void test004TaskProperties() throws Exception { addObjectFromFile(taskFilename()); - TaskQuartzImpl task = getTask(taskOid(), result); + TaskQuartzImpl task = getTaskWithResult(taskOid(), result); System.out.println("Task extension = " + task.getExtensionOrClone()); @@ -359,7 +359,7 @@ public void test004TaskProperties() throws Exception { logger.trace("Retrieving the task (second time) and comparing its properties..."); - Task task001 = getTask(taskOid(), result); + Task task001 = getTaskWithResult(taskOid(), result); logger.trace("Task from repo: " + task001.debugDump()); AssertJUnit.assertEquals(TaskBinding.LOOSE, task001.getBinding()); PrismAsserts.assertEqualsPolyString("Name not", newname, task001.getName()); @@ -442,7 +442,7 @@ public void test005Single() throws Exception { addObjectFromFile(taskFilename()); logger.trace("Retrieving the task..."); - TaskQuartzImpl task = getTask(taskOid(), result); + TaskQuartzImpl task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); logger.trace("Task retrieval OK."); @@ -457,7 +457,7 @@ public void test005Single() throws Exception { // Check task status - Task task1 = getTask(taskOid(), result); + Task task1 = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task1); System.out.println("getTask returned: " + task1.debugDump()); @@ -538,7 +538,7 @@ public void test006Cycle() throws Exception { // Check task status - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -602,7 +602,7 @@ public void test008MoreHandlers() throws Exception { // Check task status - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -655,7 +655,7 @@ public void test009CycleLoose() throws Exception { // Check task status - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -696,7 +696,7 @@ public void test010CycleCronLoose() throws Exception { // Check task status - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -738,7 +738,7 @@ public void test011MoreHandlersAndSchedules() throws Exception { // Check task status - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -798,7 +798,7 @@ public void test012Suspend() throws Exception { // check if we can read the extension (xsi:type issue) - Task taskTemp = getTask(taskOid(), result); + Task taskTemp = getTaskWithResult(taskOid(), result); PrismProperty delay = taskTemp.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); AssertJUnit.assertEquals("Delay was not read correctly", 2000, delay.getRealValue()); @@ -806,7 +806,7 @@ public void test012Suspend() throws Exception { // Check task status (task is running 5 iterations where each takes 2000 ms) - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -841,7 +841,7 @@ public void test013ReleaseAndSuspendLooselyBound() throws Exception { addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); System.out.println("After setup: " + task.debugDump()); // check if we can read the extension (xsi:type issue) @@ -897,7 +897,7 @@ public void test014SuspendLongRunning() throws Exception { addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); System.out.println("After setup: " + task.debugDump()); waitForTaskStart(taskOid(), result, 10000, 2000); @@ -1121,7 +1121,7 @@ public void test019FinishedHandler() throws Exception { // Check task status - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); AssertJUnit.assertNotNull(task); System.out.println(task.debugDump()); @@ -1234,7 +1234,7 @@ public void test022ExecuteRecurringOnDemand() throws Exception { addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); System.out.println("After setup: " + task.debugDump()); System.out.println("Waiting to see if the task would not start..."); @@ -1279,7 +1279,7 @@ public void test100LightweightSubtasks() throws Exception { addObjectFromFile(taskFilename()); String taskOid = taskOid(); - Task task = getTask(taskOid, result); + Task task = getTaskWithResult(taskOid, result); System.out.println("After setup: " + task.debugDump()); checkTaskStateRepeatedly(taskOid, result, 15000, 20); @@ -1325,7 +1325,7 @@ public void test105LightweightSubtasksSuspension() throws Exception { addObjectFromFile(taskFilename()); - Task task = getTask(taskOid(), result); + Task task = getTaskWithResult(taskOid(), result); System.out.println("After setup: " + task.debugDump()); waitForTaskStart(taskOid(), result, 15000, 500); @@ -1503,6 +1503,11 @@ public void test200RetrieveSubtasks() throws Exception { .item(TaskType.F_SUBTASK_REF).retrieve() .build(); + TaskType getTaskPlain_rootNoChildren = taskManager.getTaskPlain(rootOid, null, result).getUpdatedTaskObject().asObjectable(); + TaskType getTaskPlain_rootWithChildren = taskManager.getTaskPlain(rootOid, withChildren, result).getUpdatedTaskObject().asObjectable(); + assertEquals("Wrong # of children", 0, getTaskPlain_rootNoChildren.getSubtaskRef().size()); + assertEquals("Wrong # of children", 0, getTaskPlain_rootWithChildren.getSubtaskRef().size()); + TaskType getTask_rootNoChildren = taskManager.getTask(rootOid, null, result).getUpdatedTaskObject().asObjectable(); TaskType getTask_rootWithChildren = taskManager.getTask(rootOid, withChildren, result).getUpdatedTaskObject().asObjectable(); assertEquals("Wrong # of children", 0, getTask_rootNoChildren.getSubtaskRef().size()); @@ -1581,7 +1586,7 @@ private void checkLeftover(ArrayList leftovers, String testNumber, Strin String oid = taskOid(testNumber, subId); Task t; try { - t = getTask(oid, result); + t = getTaskWithResult(oid, result); } catch (ObjectNotFoundException e) { // this is OK, test probably did not start logger.info("Check leftovers: Task {} does not exist.", oid); @@ -1596,7 +1601,7 @@ private void checkLeftover(ArrayList leftovers, String testNumber, Strin } } - private TaskQuartzImpl getTask(String oid, OperationResult result) throws SchemaException, ObjectNotFoundException { - return taskManager.getTask(oid, retrieveItemsNamed(TaskType.F_RESULT), result); + private TaskQuartzImpl getTaskWithResult(String oid, OperationResult result) throws SchemaException, ObjectNotFoundException { + return taskManager.getTaskWithResult(oid, result); } } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java index 655eddb9907..6ef6b921854 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkBucketStrategies.java @@ -106,7 +106,7 @@ public void test100NumericExplicitBuckets() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN WorkBucketType bucket = workStateManager.getWorkBucket(task.getOid(), 0, null, null, result); @@ -115,7 +115,7 @@ public void test100NumericExplicitBuckets() throws Exception { // THEN display("allocated bucket", bucket); - TaskQuartzImpl taskAfter = taskManager.getTask(task.getOid(), result); + TaskQuartzImpl taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after", taskAfter); display("narrowed query", narrowedQuery); @@ -133,7 +133,7 @@ public void test100NumericExplicitBuckets() throws Exception { .narrowQueryForWorkBucket(task, null, UserType.class, null, bucket, result); // THEN display("allocated bucket (2)", bucket); - taskAfter = taskManager.getTask(task.getOid(), result); + taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after (2)", taskAfter); display("narrowed query (2)", narrowedQuery); assertNumericBucket(bucket, null, 2, 123, 200); @@ -153,7 +153,7 @@ public void test100NumericExplicitBuckets() throws Exception { // THEN display("allocated bucket (3)", bucket); - taskAfter = taskManager.getTask(task.getOid(), result); + taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after (3)", taskAfter); display("narrowed query (3)", narrowedQuery); @@ -170,7 +170,7 @@ public void test100NumericExplicitBuckets() throws Exception { // THEN display("allocated bucket (4)", String.valueOf(bucket)); - taskAfter = taskManager.getTask(task.getOid(), result); + taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after (4)", taskAfter); //noinspection SimplifiedTestNGAssertion @@ -186,7 +186,7 @@ public void test110FilterExplicitBuckets() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -197,7 +197,7 @@ public void test110FilterExplicitBuckets() throws Exception { // THEN display("allocated bucket", bucket); - TaskQuartzImpl taskAfter = taskManager.getTask(task.getOid(), result); + TaskQuartzImpl taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after", taskAfter); display("narrowed query", narrowedQuery); @@ -219,7 +219,7 @@ public void test110FilterExplicitBuckets() throws Exception { // THEN display("allocated bucket (2)", bucket); - taskAfter = taskManager.getTask(task.getOid(), result); + taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after (2)", taskAfter); display("narrowed query (2)", narrowedQuery); @@ -240,7 +240,7 @@ public void test110FilterExplicitBuckets() throws Exception { // THEN display("allocated bucket (3)", bucket); - taskAfter = taskManager.getTask(task.getOid(), result); + taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after (3)", taskAfter); display("narrowed query (3)", narrowedQuery); @@ -257,7 +257,7 @@ public void test110FilterExplicitBuckets() throws Exception { // THEN display("allocated bucket (4)", String.valueOf(bucket)); - taskAfter = taskManager.getTask(task.getOid(), result); + taskAfter = taskManager.getTaskPlain(task.getOid(), result); display("task after (4)", taskAfter); //noinspection SimplifiedTestNGAssertion @@ -273,7 +273,7 @@ public void test120StringPrefixBuckets() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -328,7 +328,7 @@ public void test125StringExactValueBuckets() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -383,7 +383,7 @@ public void test130StringIntervalBuckets() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -432,7 +432,7 @@ public void test140OidBuckets() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); @@ -450,7 +450,7 @@ public void test150OidBucketsTwice() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN WorkSegmentationStrategy segmentationStrategy = strategyFactory.createStrategy(task.getWorkManagement()); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java index d9e3fcc6956..6783737433d 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkDistribution.java @@ -115,15 +115,15 @@ public void test100AllocateBucket() throws Exception { addObjectFromFile(workerTaskFilename()); try { - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); + TaskQuartzImpl worker = taskManager.getTaskPlain(workerTaskOid(), result); // WHEN WorkBucketType bucket = workStateManager.getWorkBucket(worker.getOid(), 0, null, null, result); // THEN display("allocated bucket", bucket); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid(), result); - TaskQuartzImpl workerAfter = taskManager.getTask(worker.getOid(), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid(), result); + TaskQuartzImpl workerAfter = taskManager.getTaskPlain(worker.getOid(), result); display("coordinator task after", coordinatorAfter); display("worker task after", workerAfter); @@ -145,7 +145,7 @@ public void test105AllocateBucketStandalone() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); + TaskQuartzImpl standalone = taskManager.getTaskPlain(taskOid(), result); try { // WHEN @@ -153,7 +153,7 @@ public void test105AllocateBucketStandalone() throws Exception { // THEN display("allocated bucket", bucket); - TaskQuartzImpl standaloneAfter = taskManager.getTask(standalone.getOid(), result); + TaskQuartzImpl standaloneAfter = taskManager.getTaskPlain(standalone.getOid(), result); display("task after", standaloneAfter); List wBuckets = standaloneAfter.getWorkState().getBucket(); @@ -171,7 +171,7 @@ public void test107AllocateBucketStandaloneBatched() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); + TaskQuartzImpl standalone = taskManager.getTaskPlain(taskOid(), result); try { // WHEN @@ -179,7 +179,7 @@ public void test107AllocateBucketStandaloneBatched() throws Exception { // THEN display("allocated bucket", bucket); - TaskQuartzImpl standaloneAfter = taskManager.getTask(standalone.getOid(), result); + TaskQuartzImpl standaloneAfter = taskManager.getTaskPlain(standalone.getOid(), result); display("task after", standaloneAfter); List wBuckets = standaloneAfter.getWorkState().getBucket(); @@ -196,7 +196,7 @@ public void test110AllocateTwoBucketsStandalone() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl standalone = taskManager.getTask(taskOid(), result); + TaskQuartzImpl standalone = taskManager.getTaskPlain(taskOid(), result); try { // WHEN @@ -206,7 +206,7 @@ public void test110AllocateTwoBucketsStandalone() throws Exception { // THEN display("1st obtained bucket", bucket1); display("2nd obtained bucket", bucket2); - standalone = taskManager.getTask(standalone.getOid(), result); + standalone = taskManager.getTaskPlain(standalone.getOid(), result); display("task after 2xget", standalone); assertNumericBucket(bucket1, WorkBucketStateType.READY, 1, 0, 100); @@ -223,7 +223,7 @@ public void test110AllocateTwoBucketsStandalone() throws Exception { // THEN display("bucket obtained after complete", bucket3); - standalone = taskManager.getTask(standalone.getOid(), result); + standalone = taskManager.getTaskPlain(standalone.getOid(), result); display("task after complete+get", standalone); assertOptimizedCompletedBuckets(standalone); @@ -241,7 +241,7 @@ public void test110AllocateTwoBucketsStandalone() throws Exception { // THEN display("bucket obtained after 2nd complete", bucket4); - standalone = taskManager.getTask(standalone.getOid(), result); + standalone = taskManager.getTaskPlain(standalone.getOid(), result); display("task after complete+get+complete+get", standalone); assertNumericBucket(bucket4, WorkBucketStateType.READY, 3, 200, 300); @@ -262,7 +262,7 @@ public void test120UnspecifiedBuckets() throws Exception { OperationResult result = createOperationResult(); addObjectFromFile(taskFilename()); - TaskQuartzImpl task = taskManager.getTask(taskOid(), result); + TaskQuartzImpl task = taskManager.getTaskPlain(taskOid(), result); // WHEN + THEN try { @@ -284,11 +284,11 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { addObjectFromFile(taskFilename("5")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); - TaskQuartzImpl worker4 = taskManager.getTask(taskOid("4"), result); - TaskQuartzImpl worker5 = taskManager.getTask(taskOid("5"), result); + TaskQuartzImpl worker1 = taskManager.getTaskPlain(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTaskPlain(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTaskPlain(taskOid("3"), result); + TaskQuartzImpl worker4 = taskManager.getTaskPlain(taskOid("4"), result); + TaskQuartzImpl worker5 = taskManager.getTaskPlain(taskOid("5"), result); // WHEN WorkBucketType bucket1 = workStateManager.getWorkBucket(worker1.getOid(), 0, null, null, result); @@ -304,11 +304,11 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { display("3rd allocated bucket", bucket3); display("4th allocated bucket", bucket4); display("4+th allocated bucket", bucket4a); - worker1 = taskManager.getTask(worker1.getOid(), result); - worker2 = taskManager.getTask(worker2.getOid(), result); - worker3 = taskManager.getTask(worker3.getOid(), result); - worker4 = taskManager.getTask(worker4.getOid(), result); - Task coordinator = taskManager.getTask(coordinatorTaskOid(), result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); + worker2 = taskManager.getTaskPlain(worker2.getOid(), result); + worker3 = taskManager.getTaskPlain(worker3.getOid(), result); + worker4 = taskManager.getTaskPlain(worker4.getOid(), result); + Task coordinator = taskManager.getTaskPlain(coordinatorTaskOid(), result); display("coordinator task after 4+1x allocation", coordinator); display("worker1 task after 4+1x allocation", worker1); display("worker2 task after 4+1x allocation", worker2); @@ -346,9 +346,9 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { workStateManager.completeWorkBucket(worker2.getOid(), 2, null, result); // THEN - worker2 = taskManager.getTask(worker2.getOid(), result); + worker2 = taskManager.getTaskPlain(worker2.getOid(), result); display("worker2 after completion of 2nd bucket", worker2); - coordinator = taskManager.getTask(coordinator.getOid(), result); + coordinator = taskManager.getTaskPlain(coordinator.getOid(), result); display("coordinator after completion of 2nd bucket", coordinator); buckets = new ArrayList<>(coordinator.getWorkState().getBucket()); @@ -368,9 +368,9 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { WorkBucketType bucket = workStateManager.getWorkBucket(worker1.getOid(), 0, null, null, result); // THEN - worker1 = taskManager.getTask(worker1.getOid(), result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); display("worker1 after completion of 1st bucket and fetching next one", worker1); - coordinator = taskManager.getTask(coordinator.getOid(), result); + coordinator = taskManager.getTaskPlain(coordinator.getOid(), result); display("coordinator after completion of 1st bucket and fetching next one", coordinator); assertNumericBucket(bucket, null, 5, 4, 5); @@ -399,9 +399,9 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { workStateManager.releaseWorkBucket(worker4.getOid(), 4, null, result); // THEN - worker4 = taskManager.getTask(worker4.getOid(), result); + worker4 = taskManager.getTaskPlain(worker4.getOid(), result); display("worker4 after releasing of 4th bucket", worker4); - coordinator = taskManager.getTask(coordinator.getOid(), result); + coordinator = taskManager.getTaskPlain(coordinator.getOid(), result); display("coordinator after releasing of 4th bucket", coordinator); buckets = new ArrayList<>(coordinator.getWorkState().getBucket()); @@ -420,11 +420,11 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { bucket = workStateManager.getWorkBucket(worker5.getOid(), 0, null, null, result); // THEN - worker3 = taskManager.getTask(worker3.getOid(), result); + worker3 = taskManager.getTaskPlain(worker3.getOid(), result); display("worker3 after completion of 3rd bucket and getting next one", worker3); - worker5 = taskManager.getTask(worker5.getOid(), result); + worker5 = taskManager.getTaskPlain(worker5.getOid(), result); display("worker5 after completion of 3rd bucket and getting next one", worker5); - coordinator = taskManager.getTask(coordinator.getOid(), result); + coordinator = taskManager.getTaskPlain(coordinator.getOid(), result); display("coordinator after completion of 3rd bucket and getting next one", coordinator); assertNumericBucket(bucket, null, 4, 3, 4); @@ -447,11 +447,11 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { taskManager.closeTask(worker5, result); // THEN - worker1 = taskManager.getTask(worker1.getOid(), result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); display("worker1 after completion of 5th bucket and closing worker5", worker1); - worker5 = taskManager.getTask(worker5.getOid(), result); + worker5 = taskManager.getTaskPlain(worker5.getOid(), result); display("worker5 after completion of 5th bucket and closing worker5", worker5); - coordinator = taskManager.getTask(coordinator.getOid(), result); + coordinator = taskManager.getTaskPlain(coordinator.getOid(), result); display("coordinator after completion of 5th bucket and closing worker5", coordinator); buckets = new ArrayList<>(coordinator.getWorkState().getBucket()); @@ -465,9 +465,9 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { bucket = workStateManager.getWorkBucket(worker1.getOid(), 100, null, null, result); // THEN - worker1 = taskManager.getTask(worker1.getOid(), result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); display("worker1 after reclaiming mis-allocated bucket", worker1); - coordinator = taskManager.getTask(coordinator.getOid(), result); + coordinator = taskManager.getTaskPlain(coordinator.getOid(), result); display("coordinator after reclaiming mis-allocated bucket", coordinator); assertNumericBucket(bucket, null, 4, 3, 4); @@ -485,9 +485,9 @@ public void test130AllocateReleaseCompleteSequence() throws Exception { workStateManager.completeWorkBucket(worker1.getOid(), 4, null, result); // THEN - worker1 = taskManager.getTask(worker1.getOid(), result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); display("worker1 after completion of 4th bucket", worker1); - coordinator = taskManager.getTask(coordinator.getOid(), result); + coordinator = taskManager.getTaskPlain(coordinator.getOid(), result); display("coordinator after completion of 4th bucket", coordinator); buckets = new ArrayList<>(coordinator.getWorkState().getBucket()); @@ -506,7 +506,7 @@ public void test200OneWorkerTask() throws Exception { addObjectFromFile(coordinatorTaskFilename()); addObjectFromFile(workerTaskFilename()); - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); + TaskQuartzImpl worker = taskManager.getTaskPlain(workerTaskOid(), result); try { // WHEN @@ -516,8 +516,8 @@ public void test200OneWorkerTask() throws Exception { String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); - TaskQuartzImpl workerAfter = taskManager.getTask(worker.getOid(), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid, result); + TaskQuartzImpl workerAfter = taskManager.getTaskPlain(worker.getOid(), result); display("coordinator task after", coordinatorAfter); display("worker task after", workerAfter); @@ -536,9 +536,9 @@ public void test210ThreeWorkersTask() throws Exception { addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); + TaskQuartzImpl worker1 = taskManager.getTaskPlain(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTaskPlain(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTaskPlain(taskOid("3"), result); workBucketsTaskHandler.setDelayProcessor(50); @@ -551,10 +551,10 @@ public void test210ThreeWorkersTask() throws Exception { String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); - worker1 = taskManager.getTask(worker1.getOid(), result); - worker2 = taskManager.getTask(worker2.getOid(), result); - worker3 = taskManager.getTask(worker3.getOid(), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid, result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); + worker2 = taskManager.getTaskPlain(worker2.getOid(), result); + worker3 = taskManager.getTaskPlain(worker3.getOid(), result); display("coordinator task after", coordinatorAfter); display("worker1 task after", worker1); display("worker2 task after", worker2); @@ -586,9 +586,9 @@ public void test220WorkerSuspend() throws Exception { addObjectFromFile(taskFilename("2")); addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); + TaskQuartzImpl worker1 = taskManager.getTaskPlain(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTaskPlain(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTaskPlain(taskOid("3"), result); Holder suspensionVictim = new Holder<>(); workBucketsTaskHandler.setProcessor((task, bucket, index) -> { @@ -618,10 +618,10 @@ public void test220WorkerSuspend() throws Exception { waitFor("waiting for all items to be processed", () -> getTotalItemsProcessed(coordinatorTaskOid) == 107 - 6, DEFAULT_TIMEOUT, 500); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); - worker1 = taskManager.getTask(worker1.getOid(), result); - worker2 = taskManager.getTask(worker2.getOid(), result); - worker3 = taskManager.getTask(worker3.getOid(), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid, result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); + worker2 = taskManager.getTaskPlain(worker2.getOid(), result); + worker3 = taskManager.getTaskPlain(worker3.getOid(), result); display("coordinator task after unfinished run", coordinatorAfter); display("worker1 task after unfinished run", worker1); display("worker2 task after unfinished run", worker2); @@ -653,7 +653,7 @@ public void test220WorkerSuspend() throws Exception { display("Waiting for coordinator task close"); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); - coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); + coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid, result); display("coordinator task after finished run", coordinatorAfter); assertOptimizedCompletedBuckets(coordinatorAfter); @@ -674,9 +674,9 @@ public void test230WorkerException() throws Exception { addObjectFromFile(taskFilename("2")); addObjectFromFile(taskFilename("3")); try { - TaskQuartzImpl worker1 = taskManager.getTask(taskOid("1"), result); - TaskQuartzImpl worker2 = taskManager.getTask(taskOid("2"), result); - TaskQuartzImpl worker3 = taskManager.getTask(taskOid("3"), result); + TaskQuartzImpl worker1 = taskManager.getTaskPlain(taskOid("1"), result); + TaskQuartzImpl worker2 = taskManager.getTaskPlain(taskOid("2"), result); + TaskQuartzImpl worker3 = taskManager.getTaskPlain(taskOid("3"), result); Holder exceptionVictim = new Holder<>(); workBucketsTaskHandler.setProcessor((task, bucket, index) -> { @@ -702,10 +702,10 @@ public void test230WorkerException() throws Exception { waitFor("waiting for all items to be processed", () -> getTotalItemsProcessed(coordinatorTaskOid) == 107 - 6, DEFAULT_TIMEOUT, 500); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); - worker1 = taskManager.getTask(worker1.getOid(), result); - worker2 = taskManager.getTask(worker2.getOid(), result); - worker3 = taskManager.getTask(worker3.getOid(), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid, result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); + worker2 = taskManager.getTaskPlain(worker2.getOid(), result); + worker3 = taskManager.getTaskPlain(worker3.getOid(), result); display("coordinator task after unfinished run", coordinatorAfter); display("worker1 task after unfinished run", worker1); display("worker2 task after unfinished run", worker2); @@ -730,17 +730,17 @@ public void test230WorkerException() throws Exception { String oidToClose = exceptionVictim.getValue().getOid(); display("Closing task " + oidToClose); - taskManager.closeTask(taskManager.getTask(oidToClose, result), result); + taskManager.closeTask(taskManager.getTaskPlain(oidToClose, result), result); // THEN then(); display("Waiting for coordinator task close"); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); - coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); - worker1 = taskManager.getTask(worker1.getOid(), result); - worker2 = taskManager.getTask(worker2.getOid(), result); - worker3 = taskManager.getTask(worker3.getOid(), result); + coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid, result); + worker1 = taskManager.getTaskPlain(worker1.getOid(), result); + worker2 = taskManager.getTaskPlain(worker2.getOid(), result); + worker3 = taskManager.getTaskPlain(worker3.getOid(), result); display("coordinator task after", coordinatorAfter); display("worker1 task after", worker1); display("worker2 task after", worker2); @@ -769,7 +769,7 @@ public void test300NarrowQueryOneWorkerTask() throws Exception { try { - TaskQuartzImpl worker = taskManager.getTask(workerTaskOid(), result); + TaskQuartzImpl worker = taskManager.getTaskPlain(workerTaskOid(), result); // WHEN taskManager.resumeTask(worker, result); @@ -778,8 +778,8 @@ public void test300NarrowQueryOneWorkerTask() throws Exception { String coordinatorTaskOid = coordinatorTaskOid(); waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, 200); - TaskQuartzImpl coordinatorAfter = taskManager.getTask(coordinatorTaskOid, result); - TaskQuartzImpl workerAfter = taskManager.getTask(worker.getOid(), result); + TaskQuartzImpl coordinatorAfter = taskManager.getTaskPlain(coordinatorTaskOid, result); + TaskQuartzImpl workerAfter = taskManager.getTaskPlain(worker.getOid(), result); display("coordinator task after", coordinatorAfter); display("worker task after", workerAfter); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java index 3f64363305a..f3602c616d5 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestWorkersManagement.java @@ -117,7 +117,7 @@ public void test100CreateWorkersSingle() throws Exception { try { waitForTaskProgress(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + TaskQuartzImpl coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); List workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -141,7 +141,7 @@ public void test100CreateWorkersSingle() throws Exception { // THEN waitForTaskClose(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -179,7 +179,7 @@ public void test110CreateWorkersRecurring() throws Exception { then("1: import task"); waitForTaskProgress(coordinatorTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + TaskQuartzImpl coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); List workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -200,7 +200,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (worker is still present and executed) then("2: wait for coordinator next run"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); @@ -217,7 +217,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("3: suspend the tree while work is done"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); Task worker = workers.get(0); @@ -242,7 +242,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are resumed) then("4: resume the tree"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -264,7 +264,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("5: suspend the tree while worker is executing"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -289,7 +289,7 @@ public void test110CreateWorkersRecurring() throws Exception { // THEN (tasks are suspended) then("6: resume after 2nd suspend"); - coordinatorTask = taskManager.getTask(coordinatorTaskOid(), result); + coordinatorTask = taskManager.getTaskPlain(coordinatorTaskOid(), result); workers = coordinatorTask.listSubtasks(result); assertEquals("Wrong # of workers", 1, workers.size()); worker = workers.get(0); @@ -327,7 +327,7 @@ public void test200SimplePartitioning() throws Exception { try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl masterTask = taskManager.getTask(masterTaskOid, result); + TaskQuartzImpl masterTask = taskManager.getTaskPlain(masterTaskOid, result); List subtasks = masterTask.listSubtasks(result); display("master task", masterTask); @@ -343,7 +343,7 @@ public void test200SimplePartitioning() throws Exception { waitForTaskCloseCheckingSubtasks(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL); - masterTask = taskManager.getTask(masterTaskOid, result); + masterTask = taskManager.getTaskPlain(masterTaskOid, result); subtasks = masterTask.listSubtasksDeeply(result); displayBucketOpStatistics("master", masterTask); for (Task subtask : subtasks) { @@ -376,7 +376,7 @@ public void test210PartitioningToWorkersSingleBucket() throws Exception { try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl masterTask = taskManager.getTask(masterTaskOid, result); + TaskQuartzImpl masterTask = taskManager.getTaskPlain(masterTaskOid, result); List subtasks = masterTask.listSubtasks(result); display("master task", masterTask); @@ -392,7 +392,7 @@ public void test210PartitioningToWorkersSingleBucket() throws Exception { assertNotNull("Third-phase task was not created", third); waitForTaskCloseCheckingSubtasks(second.getOid(), result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL); - second = taskManager.getTask(second.getOid(), result); + second = taskManager.getTaskPlain(second.getOid(), result); display("Second task after completion", second); List secondSubtasks = second.listSubtasks(result); display("Subtasks of second task after completion", secondSubtasks); @@ -405,7 +405,7 @@ public void test210PartitioningToWorkersSingleBucket() throws Exception { secondSubtasks.forEach(t -> assertCachingProfiles(t, "profile2")); waitForTaskCloseCheckingSubtasks(third.getOid(), result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL); - third = taskManager.getTask(third.getOid(), result); + third = taskManager.getTaskPlain(third.getOid(), result); display("Third task after completion", third); List thirdSubtasks = third.listSubtasks(result); display("Subtasks of third task after completion", thirdSubtasks); @@ -439,7 +439,7 @@ public void test220PartitioningToWorkersMoreBuckets() throws Exception { try { waitForTaskProgress(masterTaskOid, result, DEFAULT_TIMEOUT, DEFAULT_SLEEP_INTERVAL, 1); - TaskQuartzImpl masterTask = taskManager.getTask(masterTaskOid, result); + TaskQuartzImpl masterTask = taskManager.getTaskPlain(masterTaskOid, result); List subtasks = masterTask.listSubtasks(result); display("master task", masterTask); @@ -455,14 +455,14 @@ public void test220PartitioningToWorkersMoreBuckets() throws Exception { assertNotNull("Third-phase task was not created", third); waitForTaskCloseCheckingSubtasks(second.getOid(), result, 30000L, DEFAULT_SLEEP_INTERVAL); - second = taskManager.getTask(second.getOid(), result); + second = taskManager.getTaskPlain(second.getOid(), result); display("Second task after completion", second); List secondSubtasks = second.listSubtasks(result); display("Subtasks of second task after completion", secondSubtasks); assertEquals("Wrong # of second task's subtasks", 3, secondSubtasks.size()); waitForTaskCloseCheckingSubtasks(third.getOid(), result, 20000L, DEFAULT_SLEEP_INTERVAL); - third = taskManager.getTask(third.getOid(), result); + third = taskManager.getTaskPlain(third.getOid(), result); display("Third task after completion", third); List thirdSubtasks = third.listSubtasks(result); display("Subtasks of third task after completion", thirdSubtasks); diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java index 97fc539e0d3..98bd09fae8e 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/TestOpenLdap.java @@ -24,8 +24,6 @@ import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.AbstractIntegrationTest; -import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.exception.ObjectNotFoundException; @@ -139,7 +137,7 @@ protected void assertActivationCapability(ActivationCapabilityType activationCap protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException { OperationResult result = createOperationResult(); - Task task = taskManager.getTask(syncTaskOid, result); + Task task = taskManager.getTaskPlain(syncTaskOid, result); result.computeStatus(); TestUtil.assertSuccess(result); diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java index d99100da1ba..bffdea986aa 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapTest.java @@ -54,7 +54,6 @@ import com.evolveum.midpoint.schema.util.ObjectQueryUtil; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.AbstractIntegrationTest; import com.evolveum.midpoint.test.IntegrationTestTools; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; @@ -1233,7 +1232,7 @@ private byte[] encodePassword(String password) { protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException { OperationResult result = createOperationResult("assertStepSyncToken"); - Task task = taskManager.getTask(syncTaskOid, result); + Task task = taskManager.getTaskPlain(syncTaskOid, result); PrismProperty syncTokenProperty = task.getExtensionPropertyOrClone(SchemaConstants.SYNC_TOKEN); assertNotNull("No sync token", syncTokenProperty); assertNotNull("No sync token value", syncTokenProperty.getRealValue()); diff --git a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java index e1d51dcf131..9236eef7cc3 100644 --- a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java +++ b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java @@ -86,7 +86,6 @@ import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectDeltaOperationListType; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ObjectListType; -import com.evolveum.midpoint.xml.ns._public.common.api_types_3.PropertyReferenceListType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @@ -2611,18 +2610,10 @@ public void test300LiveSyncInit() throws Exception { waitFor("Waiting for task manager to pick up the task", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { - Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); + Task task = taskManager.getTaskPlain(TASK_OPENDJ_SYNC_OID, result); display("Task while waiting for task manager to pick up the task", task); // wait until the task is picked up return task.getLastRunFinishTimestamp() != null; -// if (TaskExclusivityStatus.CLAIMED == task.getExclusivityStatus()) { -// // wait until the first run is finished -// if (task.getLastRunFinishTimestamp() == null) { -// return false; -// } -// return true; -// } -// return false; } @Override @@ -2633,7 +2624,7 @@ public void timeout() { // Check task status - Task task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, retrieveTaskResult(), result); + Task task = taskManager.getTaskWithResult(TASK_OPENDJ_SYNC_OID, result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); @@ -2685,7 +2676,7 @@ public void timeout() { // Try without options. The results should NOT be there // MID-4670 - task = taskManager.getTask(TASK_OPENDJ_SYNC_OID, null, result); + task = taskManager.getTaskPlain(TASK_OPENDJ_SYNC_OID, null, result); taskResult = task.getResult(); AssertJUnit.assertNull("Unexpected task result", taskResult); @@ -2701,7 +2692,7 @@ public void test301LiveSyncCreate() throws Exception { // new LDAP object. final OperationResult result = createOperationResult(); - final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); + final Task syncCycle = taskManager.getTaskPlain(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); final Object tokenBefore = findSyncToken(syncCycle); @@ -2735,7 +2726,7 @@ public void test301LiveSyncCreate() throws Exception { @Test public void test302LiveSyncModify() throws Exception { final OperationResult result = createOperationResult(); - final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); + final Task syncCycle = taskManager.getTaskPlain(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); @@ -2787,7 +2778,7 @@ public void test303LiveSyncLink() throws Exception { //create account for e which should be correlated final OperationResult result = createOperationResult(); - final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); + final Task syncCycle = taskManager.getTaskPlain(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); @@ -2829,7 +2820,7 @@ public void test304LiveSyncCreateNoLocation() throws Exception { // new LDAP object. final OperationResult result = createOperationResult(); - final Task syncCycle = taskManager.getTask(TASK_OPENDJ_SYNC_OID, result); + final Task syncCycle = taskManager.getTaskPlain(TASK_OPENDJ_SYNC_OID, result); AssertJUnit.assertNotNull(syncCycle); int tokenBefore = findSyncToken(syncCycle); @@ -3142,7 +3133,7 @@ public void test420RecomputeUsers() throws Exception { waitFor("Waiting for task to finish", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { - Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, result); + Task task = taskManager.getTaskPlain(TASK_USER_RECOMPUTE_OID, result); //display("Task while waiting for task manager to pick up the task", task); // wait until the task is finished if (TaskExecutionStatus.CLOSED == task.getExecutionStatus()) { @@ -3162,7 +3153,7 @@ public void timeout() { // Check task status - Task task = taskManager.getTask(TASK_USER_RECOMPUTE_OID, retrieveTaskResult(), result); + Task task = taskManager.getTaskWithResult(TASK_USER_RECOMPUTE_OID, result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); @@ -3294,7 +3285,7 @@ public void test440ReconcileResourceOpenDj() throws Exception { waitFor("Waiting for task to finish first run", new Checker() { public boolean check() throws ObjectNotFoundException, SchemaException { - Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result); + Task task = taskManager.getTaskPlain(TASK_OPENDJ_RECON_OID, result); display("Task while waiting for task manager to pick up the task", task); // wait until the task is finished return task.getLastRunFinishTimestamp() != null; @@ -3308,7 +3299,7 @@ public void timeout() { // Check task status - Task task = taskManager.getTask(TASK_OPENDJ_RECON_OID, result); + Task task = taskManager.getTaskPlain(TASK_OPENDJ_RECON_OID, result); result.computeStatus(); display("getTask result", result); TestUtil.assertSuccess("getTask has failed", result); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java index ae36a4e2de8..c96f660fc57 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java @@ -149,7 +149,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // and we don't need validity scanner taskManager.suspendAndDeleteTasks(Collections.singletonList(TASK_VALIDITY_SCANNER_OID), 60000L, true, initResult); - Task triggerScanner = taskManager.getTask(TASK_TRIGGER_SCANNER_OID, initResult); + Task triggerScanner = taskManager.getTaskPlain(TASK_TRIGGER_SCANNER_OID, initResult); display("triggerScanner", triggerScanner); // import of story objects From bd37a1c0acac7dc44be1d51958ee8bed953c2c36 Mon Sep 17 00:00:00 2001 From: kate Date: Tue, 10 Mar 2020 01:06:31 +0100 Subject: [PATCH 44/55] task menu item enable state fix --- .../midpoint/gui/api/page/PageBase.java | 20 ++++++++----------- 1 file changed, 8 insertions(+), 12 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java index 07021336d90..5224df38dcf 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/api/page/PageBase.java @@ -15,6 +15,8 @@ import javax.management.ObjectName; import javax.xml.namespace.QName; +import com.evolveum.midpoint.web.page.admin.PageAdminObjectDetails; + import org.apache.commons.lang.StringUtils; import org.apache.commons.lang.Validate; import org.apache.commons.lang3.ObjectUtils; @@ -1876,14 +1878,8 @@ private MainMenuItem createServerTasksItems() { addMenuItem(item, "PageAdmin.menu.top.serverTasks.nodes", PageNodes.class); - MenuItem newTaskMenu = new MenuItem(createStringResource("PageAdmin.menu.top.serverTasks.new"), GuiStyleConstants.CLASS_PLUS_CIRCLE, PageTask.class, null, - new VisibleEnableBehaviour()); - item.getItems().add(newTaskMenu); - - MenuItem menuItem = new MenuItem(createStringResource("PageAdmin.menu.top.serverTasks.edit"), - PageTask.class, null, createVisibleDisabledBehaviorForEditMenu(PageTask.class)); - item.getItems().add(menuItem); - + createFocusPageNewEditMenu(item.getItems(), "PageAdmin.menu.top.serverTasks.new", "PageAdmin.menu.top.serverTasks.edit", + PageTask.class, false); return item; @@ -2074,8 +2070,8 @@ public boolean isVisible() { return false; } - if (getPage() instanceof PageAdminFocus) { - PageAdminFocus page = (PageAdminFocus) getPage(); + if (getPage() instanceof PageAdminObjectDetails) { + PageAdminObjectDetails page = (PageAdminObjectDetails) getPage(); return page.isOidParameterExists() || page.isEditingFocus(); } else if (getPage() instanceof PageResourceWizard) { PageResourceWizard page = (PageResourceWizard) getPage(); @@ -2102,8 +2098,8 @@ protected boolean isMenuActive() { return false; } - if (PageBase.this.getPage() instanceof PageAdminFocus) { - PageAdminFocus page = (PageAdminFocus) PageBase.this.getPage(); + if (PageBase.this.getPage() instanceof PageAdminObjectDetails) { + PageAdminObjectDetails page = (PageAdminObjectDetails) PageBase.this.getPage(); return !page.isOidParameterExists() && !page.isEditingFocus(); } else if (PageBase.this.getPage() instanceof PageResourceWizard) { PageResourceWizard page = (PageResourceWizard) PageBase.this.getPage(); From 10f8d220bf57052646601abf13bbb7313548037d Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 15:30:26 +0100 Subject: [PATCH 45/55] TracerImpl decoupled from test + Tracer.setTemplateParametersCustomizer --- .../test/AbstractIntegrationTest.java | 19 +++-- .../evolveum/midpoint/task/api/Tracer.java | 17 +++- .../task/quartzimpl/tracing/TracerImpl.java | 81 ++++++++++--------- 3 files changed, 67 insertions(+), 50 deletions(-) diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index 0027d2f82a7..615ed3d0e9e 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -135,6 +135,9 @@ public abstract class AbstractIntegrationTest extends AbstractSpringTest 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 @@ -255,16 +258,14 @@ protected void postInitSystem(Task initTask, OperationResult initResult) throws * This implementation fully overrides version from {@link AbstractSpringTest}. */ @BeforeMethod - public void startTestContext(ITestResult testResult) { + public void startTestContext(ITestResult testResult) throws SchemaException { Class testClass = testResult.getMethod().getTestClass().getRealClass(); String testMethodName = testResult.getMethod().getMethodName(); - - displayTestTitle(testClass.getSimpleName() + "." + testMethodName); + String testName = testClass.getSimpleName() + "." + testMethodName; + displayTestTitle(testName); Task task = createTask(testMethodName); - // TODO inttest do we need that subresult? :-) (Virgo's brave new world) - // If this exist for some "optional richer tracing", why not switch it on with some System property? - // maybe it doesn't break tests, but changes traceability/maintenance? + // TODO inttest: add tracing facility - ideally without the need to create subresult // OperationResult rootResult = task.getResult(); // TracingProfileType tracingProfile = getTestMethodTracingProfile(); // CompiledTracingProfile compiledTracingProfile = tracingProfile != null ? @@ -278,8 +279,10 @@ public void startTestContext(ITestResult testResult) { // task.setResult(result); MidpointTestContextWithTask.create(testClass, testMethodName, task, task.getResult()); - // TODO inttest: remove after fix in TracerImpl - TestNameHolder.setCurrentTestName(contextName()); + tracer.setTemplateParametersCustomizer(params -> { + params.put(MACRO_TEST_NAME_TRACER_PARAM, testName); + params.put(MACRO_TEST_NAME_SHORT_TRACER_PARAM, testMethodName); + }); } /** diff --git a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java index ea1d1852ce3..f90f86afbd1 100644 --- a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java +++ b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java @@ -7,11 +7,16 @@ package com.evolveum.midpoint.task.api; +import java.util.Map; +import java.util.function.Consumer; + +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; + import com.evolveum.midpoint.schema.result.CompiledTracingProfile; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.TracingProfileType; -import org.jetbrains.annotations.Nullable; /** * @@ -21,8 +26,8 @@ public interface Tracer { /** * Stores trace to persistent storage (usually a file in "trace" directory). * - * @param task Task containing the context information necessary e.g. to derive name of the trace file. - * @param result Result that is to be serialized and stored. + * @param task Task containing the context information necessary e.g. to derive name of the trace file. + * @param result Result that is to be serialized and stored. * @param parentResult Parent result where this operation should be recorded (if any). */ void storeTrace(Task task, OperationResult result, @Nullable OperationResult parentResult); @@ -39,5 +44,11 @@ public interface Tracer { CompiledTracingProfile compileProfile(TracingProfileType profile, OperationResult result) throws SchemaException; + /** + * Sets customizer of tracer template parameters, replacing any previous one. + * This allows to inject custom parameters, for instance during test runs. + */ + void setTemplateParametersCustomizer(@NotNull Consumer> customizer); + //TracingLevelType getLevel(@NotNull TracingProfileType resolvedProfile, @NotNull Class traceClass); } diff --git a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/tracing/TracerImpl.java b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/tracing/TracerImpl.java index 94001b1a922..361dc356c68 100644 --- a/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/tracing/TracerImpl.java +++ b/repo/task-quartz-impl/src/main/java/com/evolveum/midpoint/task/quartzimpl/tracing/TracerImpl.java @@ -7,6 +7,27 @@ package com.evolveum.midpoint.task.quartzimpl.tracing; +import java.io.File; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.nio.charset.StandardCharsets; +import java.text.SimpleDateFormat; +import java.util.Objects; +import java.util.*; +import java.util.function.Consumer; +import java.util.stream.Collectors; +import javax.annotation.PostConstruct; +import javax.annotation.PreDestroy; + +import org.apache.commons.lang.StringUtils; +import org.apache.commons.text.StringSubstitutor; +import org.jetbrains.annotations.NotNull; +import org.jetbrains.annotations.Nullable; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.stereotype.Component; + import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration; import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.util.CloneUtil; @@ -18,7 +39,6 @@ import com.evolveum.midpoint.schema.result.CompiledTracingProfile; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.schema.util.TestNameHolder; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.task.api.Tracer; @@ -31,25 +51,6 @@ 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 org.apache.commons.lang.StringUtils; -import org.apache.commons.text.StringSubstitutor; -import org.jetbrains.annotations.NotNull; -import org.jetbrains.annotations.Nullable; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.stereotype.Component; - -import javax.annotation.PostConstruct; -import javax.annotation.PreDestroy; -import java.io.File; -import java.io.FileWriter; -import java.io.IOException; -import java.io.PrintWriter; -import java.nio.charset.StandardCharsets; -import java.text.SimpleDateFormat; -import java.util.*; -import java.util.Objects; -import java.util.stream.Collectors; /** * Manages tracing requests. @@ -58,11 +59,10 @@ public class TracerImpl implements Tracer, SystemConfigurationChangeListener { private static final Trace LOGGER = TraceManager.getTrace(TracerImpl.class); + private static final String MACRO_TIMESTAMP = "timestamp"; private static final String MACRO_OPERATION_NAME = "operationName"; private static final String MACRO_OPERATION_NAME_SHORT = "operationNameShort"; - private static final String MACRO_TEST_NAME = "testName"; - private static final String MACRO_TEST_NAME_SHORT = "testNameShort"; private static final String MACRO_FOCUS_NAME = "focusName"; private static final String MACRO_MILLISECONDS = "milliseconds"; private static final String MACRO_RANDOM = "random"; @@ -78,7 +78,7 @@ public class TracerImpl implements Tracer, SystemConfigurationChangeListener { @Qualifier("cacheRepositoryService") private transient RepositoryService repositoryService; - private SystemConfigurationType systemConfiguration; // can be null during some tests + private SystemConfigurationType systemConfiguration; // can be null during some tests private static final String OP_STORE_TRACE = TracerImpl.class.getName() + ".storeTrace"; @@ -87,6 +87,11 @@ public class TracerImpl implements Tracer, SystemConfigurationChangeListener { private static final String DEFAULT_FILE_NAME_PATTERN = "trace-%{timestamp}"; + public static final Consumer> DEFAULT_TEMPLATE_PARAMETERS_CUSTOMIZER = params -> { + }; + + @NotNull private Consumer> templateParametersCustomizer = DEFAULT_TEMPLATE_PARAMETERS_CUSTOMIZER; + @PostConstruct public void init() { systemConfigurationChangeDispatcher.registerListener(this); @@ -113,7 +118,7 @@ public void storeTrace(Task task, OperationResult result, @Nullable OperationRes if (!Boolean.FALSE.equals(tracingProfile.isCreateTraceFile())) { boolean zip = !Boolean.FALSE.equals(tracingProfile.isCompressOutput()); - Map templateParameters = createTemplateParameters(task, result); // todo evaluate lazily if needed + Map templateParameters = createTemplateParameters(result); // todo evaluate lazily if needed File file = createFileName(zip, tracingProfile, templateParameters); try { long start = System.currentTimeMillis(); @@ -282,7 +287,7 @@ private String findOrCreateEntry(PrismObject object) { } int newEntryId = maxEntryId + 1; LOGGER.trace("Inserting object as entry #{}:{}: {} [in {} ms]", dictionaryId, newEntryId, objectToStore, - System.currentTimeMillis()-started); + System.currentTimeMillis() - started); dictionary.beginEntry() .identifier(newEntryId) @@ -321,7 +326,7 @@ private PrismObject stripFetchResult(PrismObject extractDictionary(partialResult, extractingVisitor)); } - private Map createTemplateParameters(Task task, OperationResult result) { + private Map createTemplateParameters(OperationResult result) { Map rv = new HashMap<>(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss-SSS"); rv.put(MACRO_TIMESTAMP, df.format(new Date())); String operationName = result.getOperation(); rv.put(MACRO_OPERATION_NAME, operationName); rv.put(MACRO_OPERATION_NAME_SHORT, shorten(operationName)); - String testName; - // TODO inttest: subclass TracerImpl in test scope with change here (use template method) - if (TestNameHolder.getCurrentTestName() != null) { - testName = TestNameHolder.getCurrentTestName(); - } else { - testName = task.getResult().getOperation(); - } - rv.put(MACRO_TEST_NAME, testName); // e.g. com.evolveum.midpoint.model.intest.TestIteration.test532GuybrushModifyDescription or simply TestIteration.test532GuybrushModifyDescription - rv.put(MACRO_TEST_NAME_SHORT, shorten(testName)); rv.put(MACRO_FOCUS_NAME, getFocusName(result)); rv.put(MACRO_MILLISECONDS, getMilliseconds(result)); - rv.put(MACRO_RANDOM, String.valueOf((long) (Math.random() * 1000000000000000L))); + rv.put(MACRO_RANDOM, String.valueOf((long) (Math.random() * 1_000_000_000_000_000L))); + templateParametersCustomizer.accept(rv); return rv; } + @Override + public void setTemplateParametersCustomizer( + @NotNull Consumer> customizer) { + templateParametersCustomizer = Objects.requireNonNull(customizer, "templateParametersCustomizer"); + } + private String shorten(String qualifiedName) { if (qualifiedName != null) { int secondLastDotIndex = StringUtils.lastOrdinalIndexOf(qualifiedName, ".", 2); - return secondLastDotIndex >= 0 ? qualifiedName.substring(secondLastDotIndex+1) : qualifiedName; + return secondLastDotIndex >= 0 ? qualifiedName.substring(secondLastDotIndex + 1) : qualifiedName; } else { return null; } @@ -471,7 +474,7 @@ private TracingProfileType getResolvedProfile(String ref, TracingConfigurationTy } resolutionPath.add(ref); TracingProfileType profile = findProfile(ref, tracingConfiguration); - resolutionPath.remove(resolutionPath.size()-1); + resolutionPath.remove(resolutionPath.size() - 1); TracingProfileType rv = resolveProfile(profile, tracingConfiguration, resolutionPath); LOGGER.info("Resolved '{}' into:\n{}", ref, rv.asPrismContainerValue().debugDump()); return rv; From c1253ac1af84ba2e7476fdd1686ab8f725999eaa Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 15:36:19 +0100 Subject: [PATCH 46/55] TestQuartzTaskManagerContract: cleanup of 004 test, there can be only 1 XML file name changed to match the test name again. --- .../quartzimpl/TestTaskManagerContract.java | 408 ++++-------------- ...operty.xml => task-004TaskBigProperty.xml} | 0 .../basic/task-004TaskProperties.xml | 31 -- .../basic/task-004bTaskBigProperty.xml | 29 -- .../basic/task-004cReferenceInExtension.xml | 27 -- 5 files changed, 78 insertions(+), 417 deletions(-) rename repo/task-quartz-impl/src/test/resources/basic/{task-004aTaskBigProperty.xml => task-004TaskBigProperty.xml} (100%) delete mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-004TaskProperties.xml delete mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-004bTaskBigProperty.xml delete mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-004cReferenceInExtension.xml diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java index 9ca04d4f1ae..d78fc29ff7d 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java @@ -10,7 +10,6 @@ import static org.testng.AssertJUnit.*; -import static com.evolveum.midpoint.task.quartzimpl.TaskTestUtil.createExtensionDelta; import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; import java.io.IOException; @@ -33,14 +32,12 @@ import org.testng.annotations.Test; import org.xml.sax.SAXException; -import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.ItemDelta; -import com.evolveum.midpoint.prism.delta.PropertyDelta; +import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismProperty; +import com.evolveum.midpoint.prism.PrismPropertyDefinition; import com.evolveum.midpoint.prism.path.ItemName; -import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.query.ObjectFilter; -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.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; @@ -48,7 +45,10 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; -import com.evolveum.midpoint.task.api.*; +import com.evolveum.midpoint.task.api.RunningTask; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.task.api.TaskConstants; +import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.task.quartzimpl.cluster.ClusterManager; import com.evolveum.midpoint.task.quartzimpl.execution.JobExecutor; import com.evolveum.midpoint.test.Checker; @@ -127,72 +127,8 @@ public void test003GetProgress() throws Exception { AssertJUnit.assertEquals("Progress is not 0", 0, task.getProgress()); } - @Test(enabled = false) // this is probably OK to fail, so do not enable it (at least for now) - public void test004aTaskBigProperty() throws Exception { - OperationResult result = createOperationResult(); - - String string300 = "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-"; - String string300a = "AAAAAAAAA-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-" - + "123456789-123456789-123456789-123456789-123456789-"; - - addObjectFromFile(taskFilename()); - - TaskQuartzImpl task = getTaskWithResult(taskOid(), result); - - // property definition - ItemName bigStringQName = new ItemName("http://midpoint.evolveum.com/repo/test", "bigString"); - MutablePrismPropertyDefinition bigStringDefinition = prismContext.definitionFactory() - .createPropertyDefinition(bigStringQName, DOMUtil.XSD_STRING); - bigStringDefinition.setIndexed(false); - bigStringDefinition.setMinOccurs(0); - bigStringDefinition.setMaxOccurs(1); - System.out.println("bigstring property definition = " + bigStringDefinition); - - PrismProperty bigStringProperty = (PrismProperty) bigStringDefinition.instantiate(); - bigStringProperty.setRealValue(string300); - task.setExtensionProperty(bigStringProperty); - - task.flushPendingModifications(result); - - System.out.println("1st round: Task = " + task.debugDump()); - - logger.trace("Retrieving the task and comparing its properties..."); - - Task task001 = getTaskWithResult(taskOid(), result); - System.out.println("1st round: Task from repo: " + task001.debugDump()); - - PrismProperty bigString001 = task001.getExtensionPropertyOrClone(bigStringQName); - assertEquals("Big string not retrieved correctly (1st round)", bigStringProperty.getRealValue(), bigString001.getRealValue()); - - // second round - - bigStringProperty.setRealValue(string300a); - task001.setExtensionProperty(bigStringProperty); - - // brutal hack, because task extension property has no "indexed" flag when retrieved from repo - task001.getExtensionPropertyOrClone(bigStringQName).getDefinition().toMutable().setIndexed(false); - - System.out.println("2nd round: Task before save = " + task001.debugDump()); - task001.flushPendingModifications(result); // however, this does not work, because 'modifyObject' in repo first reads object, overwriting any existing definitions ... - - Task task002 = getTaskWithResult(taskOid(), result); - System.out.println("2nd round: Task from repo: " + task002.debugDump()); - - PrismProperty bigString002 = task002.getExtensionPropertyOrClone(bigStringQName); - assertEquals("Big string not retrieved correctly (2nd round)", bigStringProperty.getRealValue(), bigString002.getRealValue()); - } - @Test - public void test004bTaskBigProperty() throws Exception { + public void test004TaskBigProperty() throws Exception { OperationResult result = createOperationResult(); String string300 = "123456789-123456789-123456789-123456789-123456789-" @@ -208,9 +144,7 @@ public void test004bTaskBigProperty() throws Exception { + "123456789-123456789-123456789-123456789-123456789-" + "123456789-123456789-123456789-123456789-123456789-"; - // TODO inttest: TEST_NAME was set to "test004aTaskBigProperty"; WHY a and not b? it fails with B now. - // TODO fix B file or what, so we can have this here: addObjectFromFile(taskFilename()); - addObjectFromFile("src/test/resources/basic/task-004aTaskBigProperty.xml"); + addObjectFromFile(taskFilename()); TaskQuartzImpl task = getTaskWithResult(taskOid(), result); @@ -250,183 +184,6 @@ public void test004bTaskBigProperty() throws Exception { assertEquals("Big string not retrieved correctly (2nd round)", shipStateProperty.getRealValue(), bigString002.getRealValue()); } - @Test(enabled = false) - public void test004cReferenceInExtension() throws Exception { // ok to fail - OperationResult result = createOperationResult(); - addObjectFromFile(taskFilename()); - - TaskQuartzImpl task = getTaskWithResult(taskOid(), result); - - System.out.println("Task extension = " + task.getExtensionOrClone()); - - //PrismObject requestee = task.getOwner(); - //task.setRequesteeRef(requestee); - - //LOGGER.trace("Saving modifications..."); - //task.flushPendingModifications(result); // here it crashes - - //LOGGER.trace("Retrieving the task and comparing its properties..."); - //Task task001 = getTask(taskOid(test), result); - //LOGGER.trace("Task from repo: " + task001.debugDump()); - //AssertJUnit.assertEquals("RequesteeRef was not stored/retrieved correctly", requestee.getOid(), task001.getRequesteeRef().getOid()); - } - - @Test(enabled = false) - public void test004TaskProperties() throws Exception { - OperationResult result = createOperationResult(); - - addObjectFromFile(taskFilename()); - - TaskQuartzImpl task = getTaskWithResult(taskOid(), result); - - System.out.println("Task extension = " + task.getExtensionOrClone()); - - PrismPropertyDefinition delayDefinition = prismContext.definitionFactory().createPropertyDefinition(SchemaConstants.NOOP_DELAY_QNAME, DOMUtil.XSD_INT); - System.out.println("property definition = " + delayDefinition); - - PrismProperty property = (PrismProperty) delayDefinition.instantiate(); - property.setRealValue(100); - - PropertyDelta delta = prismContext.deltaFactory().property().create(ItemPath.create(TaskType.F_EXTENSION, property.getElementName()), property.getDefinition()); - //delta.addV(property.getValues()); - delta.setValuesToReplace(PrismValueCollectionsUtil.cloneCollection(property.getValues())); - - Collection> modifications = new ArrayList<>(1); - modifications.add(delta); - - // TODO fix this code -// Collection idts = DeltaConvertor.toPropertyModificationTypes(delta); -// for (ItemDeltaType idt : idts) { -// String idtxml = prismContext.getParserDom().marshalElementToString(idt, new QName("http://a/", "A")); -// System.out.println("item delta type = " + idtxml); -// -// ItemDeltaType idt2 = prismContext.getPrismJaxbProcessor().unmarshalObject(idtxml, ItemDeltaType.class); -// ItemDelta id2 = DeltaConvertor.createItemDelta(idt2, TaskType.class, prismContext); -// System.out.println("unwrapped item delta = " + id2.debugDump()); -// -// task.modifyExtension(id2); -// } - - task.flushPendingModifications(result); - System.out.println("Task = " + task.debugDump()); - - repositoryService.getObject(UserType.class, TASK_OWNER2_OID, null, result); - - task.setBindingImmediate(TaskBinding.LOOSE, result); - - // other properties will be set in batched mode - String newname = "Test task, name changed"; - task.setName(PrismTestUtil.createPolyStringType(newname)); - task.setProgress(10L); - long currentTime = System.currentTimeMillis(); - long currentTime1 = currentTime + 10000; - long currentTime2 = currentTime + 25000; - task.setLastRunStartTimestamp(currentTime); - task.setLastRunFinishTimestamp(currentTime1); - task.setExecutionStatus(TaskExecutionStatus.SUSPENDED); - task.setHandlerUri("http://no-handler.org/"); - //task.setOwner(owner2); - - ScheduleType st0 = task.getSchedule(); - - ScheduleType st1 = new ScheduleType(); - st1.setInterval(1); - st1.setMisfireAction(MisfireActionType.RESCHEDULE); - task.pushHandlerUri("http://no-handler.org/1", st1, TaskBinding.TIGHT, createExtensionDelta(delayDefinition, 1, - prismContext)); - - ScheduleType st2 = new ScheduleType(); - st2.setInterval(2); - st2.setMisfireAction(MisfireActionType.EXECUTE_IMMEDIATELY); - task.pushHandlerUri("http://no-handler.org/2", st2, TaskBinding.LOOSE, createExtensionDelta(delayDefinition, 2, - prismContext)); - - task.setRecurrenceStatus(TaskRecurrence.RECURRING); - - OperationResultType ort = result.createOperationResultType(); // to be compared with later - - task.setResult(result); - - ObjectReferenceType objectReferenceType = new ObjectReferenceType(); - objectReferenceType.setType(UserType.COMPLEX_TYPE); - String objectOid = "some-oid..."; - objectReferenceType.setOid(objectOid); - task.setObjectRef(objectReferenceType); - - logger.trace("Saving modifications..."); - - task.flushPendingModifications(result); - - logger.trace("Retrieving the task (second time) and comparing its properties..."); - - Task task001 = getTaskWithResult(taskOid(), result); - logger.trace("Task from repo: " + task001.debugDump()); - AssertJUnit.assertEquals(TaskBinding.LOOSE, task001.getBinding()); - PrismAsserts.assertEqualsPolyString("Name not", newname, task001.getName()); -// AssertJUnit.assertEquals(newname, task001.getName()); - assertEquals(task001.getProgress(), 10); - AssertJUnit.assertNotNull(task001.getLastRunStartTimestamp()); - AssertJUnit.assertEquals("Start time is not correct", (Long) (currentTime / 1000L), (Long) (task001.getLastRunStartTimestamp() / 1000L)); // e.g. MySQL cuts off millisecond information - AssertJUnit.assertNotNull(task001.getLastRunFinishTimestamp()); - AssertJUnit.assertEquals("Finish time is not correct", (Long) (currentTime1 / 1000L), (Long) (task001.getLastRunFinishTimestamp() / 1000L)); -// AssertJUnit.assertEquals(TaskExclusivityStatus.CLAIMED, task001.getExclusivityStatus()); - AssertJUnit.assertEquals(TaskExecutionStatus.SUSPENDED, task001.getExecutionStatus()); - AssertJUnit.assertEquals("Handler after 2xPUSH is not OK", "http://no-handler.org/2", task001.getHandlerUri()); - AssertJUnit.assertEquals("Schedule after 2xPUSH is not OK", st2, task001.getSchedule()); - AssertJUnit.assertEquals("Number of handlers is not OK", 3, task.getHandlersCount()); - UriStack us = task.getOtherHandlersUriStack(); - AssertJUnit.assertEquals("First handler from the handler stack does not match", "http://no-handler.org/", us.getUriStackEntry().get(0).getHandlerUri()); - AssertJUnit.assertEquals("First schedule from the handler stack does not match", st0, us.getUriStackEntry().get(0).getSchedule()); - AssertJUnit.assertEquals("Second handler from the handler stack does not match", "http://no-handler.org/1", us.getUriStackEntry().get(1).getHandlerUri()); - AssertJUnit.assertEquals("Second schedule from the handler stack does not match", st1, us.getUriStackEntry().get(1).getSchedule()); - AssertJUnit.assertTrue(task001.isRecurring()); - OperationResult r001 = task001.getResult(); - AssertJUnit.assertNotNull(r001); - //AssertJUnit.assertEquals("Owner OID is not correct", TASK_OWNER2_OID, task001.getOwner().getOid()); - - PrismProperty d = task001.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME); - AssertJUnit.assertNotNull("delay extension property was not found", d); - AssertJUnit.assertEquals("delay extension property has wrong value", (Integer) 100, d.getRealValue(Integer.class)); - - OperationResultType ort1 = r001.createOperationResultType(); - - // handling of operation result in tasks is extremely fragile now... - // in case of problems, just uncomment the following line ;) - AssertJUnit.assertEquals(ort, ort1); - - //AssertJUnit.assertEquals("RequesteeRef was not stored/retrieved correctly", requestee.getOid(), task001.getRequesteeRef().getOid()); - //AssertJUnit.assertEquals("RequesteeOid was not stored/retrieved correctly", requestee.getOid(), task001.getRequesteeOid()); - - AssertJUnit.assertEquals("ObjectRef OID was not stored/retrieved correctly", objectReferenceType.getOid(), task001.getObjectRefOrClone().getOid()); - AssertJUnit.assertEquals("ObjectRef ObjectType was not stored/retrieved correctly", objectReferenceType.getType(), task001.getObjectRefOrClone().getType()); - - // now pop the handlers - - task001.finishHandler(result); - task001.refresh(result); - AssertJUnit.assertEquals("Handler URI after first POP is not correct", "http://no-handler.org/1", task001.getHandlerUri()); - AssertJUnit.assertEquals("Schedule after first POP is not correct", st1, task001.getSchedule()); - AssertJUnit.assertEquals("Binding after first POP is not correct", TaskBinding.TIGHT, task001.getBinding()); - AssertJUnit.assertNotSame("Task state after first POP should not be CLOSED", TaskExecutionStatus.CLOSED, task001.getExecutionStatus()); - AssertJUnit.assertEquals("Extension element value is not correct after first POP", (Integer) 2, task001.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME).getRealValue(Integer.class)); - - task001.finishHandler(result); - task001.refresh(result); - AssertJUnit.assertEquals("Handler URI after second POP is not correct", "http://no-handler.org/", task001.getHandlerUri()); - AssertJUnit.assertEquals("Schedule after second POP is not correct", st0, task001.getSchedule()); - AssertJUnit.assertEquals("Binding after second POP is not correct", TaskBinding.LOOSE, task001.getBinding()); - AssertJUnit.assertNotSame("Task state after second POP should not be CLOSED", TaskExecutionStatus.CLOSED, task001.getExecutionStatus()); - AssertJUnit.assertEquals("Extension element value is not correct after second POP", (Integer) 1, task001.getExtensionPropertyOrClone(SchemaConstants.NOOP_DELAY_QNAME).getRealValue(Integer.class)); - - task001.finishHandler(result); - task001.refresh(result); - //AssertJUnit.assertNull("Handler URI after third POP is not null", task001.getHandlerUri()); - AssertJUnit.assertEquals("Handler URI after third POP is not correct", "http://no-handler.org/", task001.getHandlerUri()); - AssertJUnit.assertEquals("Task state after third POP is not CLOSED", TaskExecutionStatus.CLOSED, task001.getExecutionStatus()); - - } - - /* * Execute a single-run task. */ @@ -981,89 +738,80 @@ public boolean check() { public void timeout() { } }, 10000, 2000); - } @Test public void test016WaitForSubtasks() throws Exception { final OperationResult result = createOperationResult(); - //taskManager.getClusterManager().startClusterManagerThread(); - - try { - - Task rootTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename()), result); - Task firstChildTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename("-child-1")), result); - - Task firstReloaded = taskManager.getTaskByIdentifier(firstChildTask.getTaskIdentifier(), result); - assertEquals("Didn't get correct task by identifier", firstChildTask.getOid(), firstReloaded.getOid()); - - Task secondChildTask = rootTask.createSubtask(); - secondChildTask.setName("Second child"); - secondChildTask.setOwner(rootTask.getOwner()); - secondChildTask.pushHandlerUri(SINGLE_TASK_HANDLER_URI, new ScheduleType(), null); - secondChildTask.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); // will resume it after root starts waiting for tasks - taskManager.switchToBackground(secondChildTask, result); - - Task firstPrerequisiteTask = taskManager.createTaskInstance( - addObjectFromFile(taskFilename("-prerequisite-1")), result); - - List prerequisities = rootTask.listPrerequisiteTasks(result); - assertEquals("Wrong # of prerequisite tasks", 1, prerequisities.size()); - assertEquals("Wrong OID of prerequisite task", firstPrerequisiteTask.getOid(), prerequisities.get(0).getOid()); - - Task secondPrerequisiteTask = taskManager.createTaskInstance(); - secondPrerequisiteTask.setName("Second prerequisite"); - secondPrerequisiteTask.setOwner(rootTask.getOwner()); - secondPrerequisiteTask.addDependent(rootTask.getTaskIdentifier()); - secondPrerequisiteTask.pushHandlerUri(TaskConstants.NOOP_TASK_HANDLER_URI, new ScheduleType(), null); - secondPrerequisiteTask.setExtensionPropertyValue(SchemaConstants.NOOP_DELAY_QNAME, 1500); - secondPrerequisiteTask.setExtensionPropertyValue(SchemaConstants.NOOP_STEPS_QNAME, 1); - secondPrerequisiteTask.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); // will resume it after root starts waiting for tasks - secondPrerequisiteTask.addDependent(rootTask.getTaskIdentifier()); - taskManager.switchToBackground(secondPrerequisiteTask, result); - - logger.info("Starting waiting for child/prerequisite tasks"); - rootTask.startWaitingForTasksImmediate(result); - - firstChildTask.refresh(result); - assertEquals("Parent is not set correctly on 1st child task", rootTask.getTaskIdentifier(), firstChildTask.getParent()); - secondChildTask.refresh(result); - assertEquals("Parent is not set correctly on 2nd child task", rootTask.getTaskIdentifier(), secondChildTask.getParent()); - firstPrerequisiteTask.refresh(result); - assertEquals("Dependents are not set correctly on 1st prerequisite task (count differs)", 1, firstPrerequisiteTask.getDependents().size()); - assertEquals("Dependents are not set correctly on 1st prerequisite task (value differs)", rootTask.getTaskIdentifier(), firstPrerequisiteTask.getDependents().get(0)); - List deps = firstPrerequisiteTask.listDependents(result); - assertEquals("Dependents are not set correctly on 1st prerequisite task - listDependents - (count differs)", 1, deps.size()); - assertEquals("Dependents are not set correctly on 1st prerequisite task - listDependents - (value differs)", rootTask.getOid(), deps.get(0).getOid()); - secondPrerequisiteTask.refresh(result); - assertEquals("Dependents are not set correctly on 2nd prerequisite task (count differs)", 1, secondPrerequisiteTask.getDependents().size()); - assertEquals("Dependents are not set correctly on 2nd prerequisite task (value differs)", rootTask.getTaskIdentifier(), secondPrerequisiteTask.getDependents().get(0)); - deps = secondPrerequisiteTask.listDependents(result); - assertEquals("Dependents are not set correctly on 2nd prerequisite task - listDependents - (count differs)", 1, deps.size()); - assertEquals("Dependents are not set correctly on 2nd prerequisite task - listDependents - (value differs)", rootTask.getOid(), deps.get(0).getOid()); - - logger.info("Resuming suspended child/prerequisite tasks"); - taskManager.resumeTask(secondChildTask, result); - taskManager.resumeTask(secondPrerequisiteTask, result); - - final String rootOid = taskOid(); - - waitForTaskClose(rootOid, result, 60000, 3000); - - firstChildTask.refresh(result); - secondChildTask.refresh(result); - firstPrerequisiteTask.refresh(result); - secondPrerequisiteTask.refresh(result); - - assertEquals("1st child task should be closed", TaskExecutionStatus.CLOSED, firstChildTask.getExecutionStatus()); - assertEquals("2nd child task should be closed", TaskExecutionStatus.CLOSED, secondChildTask.getExecutionStatus()); - assertEquals("1st prerequisite task should be closed", TaskExecutionStatus.CLOSED, firstPrerequisiteTask.getExecutionStatus()); - assertEquals("2nd prerequisite task should be closed", TaskExecutionStatus.CLOSED, secondPrerequisiteTask.getExecutionStatus()); - - } finally { -// taskManager.getClusterManager().stopClusterManagerThread(10000L, result); - } + Task rootTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename()), result); + Task firstChildTask = taskManager.createTaskInstance(addObjectFromFile(taskFilename("-child-1")), result); + + Task firstReloaded = taskManager.getTaskByIdentifier(firstChildTask.getTaskIdentifier(), result); + assertEquals("Didn't get correct task by identifier", firstChildTask.getOid(), firstReloaded.getOid()); + + Task secondChildTask = rootTask.createSubtask(); + secondChildTask.setName("Second child"); + secondChildTask.setOwner(rootTask.getOwner()); + secondChildTask.pushHandlerUri(SINGLE_TASK_HANDLER_URI, new ScheduleType(), null); + secondChildTask.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); // will resume it after root starts waiting for tasks + taskManager.switchToBackground(secondChildTask, result); + + Task firstPrerequisiteTask = taskManager.createTaskInstance( + addObjectFromFile(taskFilename("-prerequisite-1")), result); + + List prerequisities = rootTask.listPrerequisiteTasks(result); + assertEquals("Wrong # of prerequisite tasks", 1, prerequisities.size()); + assertEquals("Wrong OID of prerequisite task", firstPrerequisiteTask.getOid(), prerequisities.get(0).getOid()); + + Task secondPrerequisiteTask = taskManager.createTaskInstance(); + secondPrerequisiteTask.setName("Second prerequisite"); + secondPrerequisiteTask.setOwner(rootTask.getOwner()); + secondPrerequisiteTask.addDependent(rootTask.getTaskIdentifier()); + secondPrerequisiteTask.pushHandlerUri(TaskConstants.NOOP_TASK_HANDLER_URI, new ScheduleType(), null); + secondPrerequisiteTask.setExtensionPropertyValue(SchemaConstants.NOOP_DELAY_QNAME, 1500); + secondPrerequisiteTask.setExtensionPropertyValue(SchemaConstants.NOOP_STEPS_QNAME, 1); + secondPrerequisiteTask.setInitialExecutionStatus(TaskExecutionStatus.SUSPENDED); // will resume it after root starts waiting for tasks + secondPrerequisiteTask.addDependent(rootTask.getTaskIdentifier()); + taskManager.switchToBackground(secondPrerequisiteTask, result); + + logger.info("Starting waiting for child/prerequisite tasks"); + rootTask.startWaitingForTasksImmediate(result); + + firstChildTask.refresh(result); + assertEquals("Parent is not set correctly on 1st child task", rootTask.getTaskIdentifier(), firstChildTask.getParent()); + secondChildTask.refresh(result); + assertEquals("Parent is not set correctly on 2nd child task", rootTask.getTaskIdentifier(), secondChildTask.getParent()); + firstPrerequisiteTask.refresh(result); + assertEquals("Dependents are not set correctly on 1st prerequisite task (count differs)", 1, firstPrerequisiteTask.getDependents().size()); + assertEquals("Dependents are not set correctly on 1st prerequisite task (value differs)", rootTask.getTaskIdentifier(), firstPrerequisiteTask.getDependents().get(0)); + List deps = firstPrerequisiteTask.listDependents(result); + assertEquals("Dependents are not set correctly on 1st prerequisite task - listDependents - (count differs)", 1, deps.size()); + assertEquals("Dependents are not set correctly on 1st prerequisite task - listDependents - (value differs)", rootTask.getOid(), deps.get(0).getOid()); + secondPrerequisiteTask.refresh(result); + assertEquals("Dependents are not set correctly on 2nd prerequisite task (count differs)", 1, secondPrerequisiteTask.getDependents().size()); + assertEquals("Dependents are not set correctly on 2nd prerequisite task (value differs)", rootTask.getTaskIdentifier(), secondPrerequisiteTask.getDependents().get(0)); + deps = secondPrerequisiteTask.listDependents(result); + assertEquals("Dependents are not set correctly on 2nd prerequisite task - listDependents - (count differs)", 1, deps.size()); + assertEquals("Dependents are not set correctly on 2nd prerequisite task - listDependents - (value differs)", rootTask.getOid(), deps.get(0).getOid()); + + logger.info("Resuming suspended child/prerequisite tasks"); + taskManager.resumeTask(secondChildTask, result); + taskManager.resumeTask(secondPrerequisiteTask, result); + + final String rootOid = taskOid(); + + waitForTaskClose(rootOid, result, 60000, 3000); + + firstChildTask.refresh(result); + secondChildTask.refresh(result); + firstPrerequisiteTask.refresh(result); + secondPrerequisiteTask.refresh(result); + + assertEquals("1st child task should be closed", TaskExecutionStatus.CLOSED, firstChildTask.getExecutionStatus()); + assertEquals("2nd child task should be closed", TaskExecutionStatus.CLOSED, secondChildTask.getExecutionStatus()); + assertEquals("1st prerequisite task should be closed", TaskExecutionStatus.CLOSED, firstPrerequisiteTask.getExecutionStatus()); + assertEquals("2nd prerequisite task should be closed", TaskExecutionStatus.CLOSED, secondPrerequisiteTask.getExecutionStatus()); } @Test diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-004aTaskBigProperty.xml b/repo/task-quartz-impl/src/test/resources/basic/task-004TaskBigProperty.xml similarity index 100% rename from repo/task-quartz-impl/src/test/resources/basic/task-004aTaskBigProperty.xml rename to repo/task-quartz-impl/src/test/resources/basic/task-004TaskBigProperty.xml diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-004TaskProperties.xml b/repo/task-quartz-impl/src/test/resources/basic/task-004TaskProperties.xml deleted file mode 100644 index 3b57217b5cb..00000000000 --- a/repo/task-quartz-impl/src/test/resources/basic/task-004TaskProperties.xml +++ /dev/null @@ -1,31 +0,0 @@ - - - - - - - - Passive task 0004 - - 91919190-76e0-59e2-86d6-3d4f02d30004 - - - waiting - - http://midpoint.evolveum.com/test/single-task-handler - - single - diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-004bTaskBigProperty.xml b/repo/task-quartz-impl/src/test/resources/basic/task-004bTaskBigProperty.xml deleted file mode 100644 index b907a66c7ef..00000000000 --- a/repo/task-quartz-impl/src/test/resources/basic/task-004bTaskBigProperty.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - Passive task 0004 - - - 91919190-76e0-59e2-86d6-3d4f02d30004 - - - waiting - - http://midpoint.evolveum.com/test/single-task-handler - - single - diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-004cReferenceInExtension.xml b/repo/task-quartz-impl/src/test/resources/basic/task-004cReferenceInExtension.xml deleted file mode 100644 index 2397fb7c503..00000000000 --- a/repo/task-quartz-impl/src/test/resources/basic/task-004cReferenceInExtension.xml +++ /dev/null @@ -1,27 +0,0 @@ - - - - - - - - Passive task 0004 - - 91919190-76e0-59e2-86d6-3d4f02d30004 - - - waiting - - http://midpoint.evolveum.com/test/single-task-handler - - single - From be6e59bf19c524273c6fb6549dfc45570ae60395 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 16:28:14 +0100 Subject: [PATCH 47/55] TestDummyParallelism: fixed task treatment for original reliability Working with OperationResults is not thread-safe, I know it now. AbstractIntegrationTest: related javadoc fixes around tasks --- .../impl/dummy/TestDummyParallelism.java | 59 ++++++++++++------- .../test/AbstractIntegrationTest.java | 12 +++- 2 files changed, 47 insertions(+), 24 deletions(-) diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java index b13e941940d..1c1af773c49 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummyParallelism.java @@ -209,15 +209,17 @@ public void test200ParallelCreate() throws Exception { accountMorganOid = null; + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { - OperationResult localResult = task.getResult().createSubresult("thread-" + i); + Task localTask = createTask(testName + "-thread-" + i); + OperationResult localResult = localTask.getResult(); ShadowType account = parseObjectType(ACCOUNT_MORGAN_FILE, ShadowType.class); try { String thisAccountMorganOid = provisioningService.addObject( - account.asPrismObject(), null, null, task, localResult); + account.asPrismObject(), null, null, localTask, localResult); successCounter.click(); synchronized (dummyResource) { @@ -298,9 +300,11 @@ private PrismObject parallelModifyTest( // WHEN when(); + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { - OperationResult localResult = task.getResult().createSubresult("thread-" + i); + Task localTask = createTask(testName + "-thread-" + i); + OperationResult localResult = localTask.getResult(); RepositoryCache.enter(cacheConfigurationManager); // Playing with cache, trying to make a worst case @@ -312,7 +316,7 @@ private PrismObject parallelModifyTest( ObjectDelta delta = deltaProducer.run(); display("ObjectDelta", delta); - provisioningService.modifyObject(ShadowType.class, accountMorganOid, delta.getModifications(), null, null, task, localResult); + provisioningService.modifyObject(ShadowType.class, accountMorganOid, delta.getModifications(), null, null, localTask, localResult); localResult.computeStatus(); display("Thread " + Thread.currentThread().getName() + " DONE, result", localResult); @@ -353,16 +357,17 @@ public void test209ParallelDelete() throws Exception { // WHEN when(); - Task task = getTestTask(); + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { - OperationResult localResult = task.getResult().createSubresult("thread-" + i); + Task localTask = createTask(testName + "-thread-" + i); + OperationResult localResult = localTask.getResult(); RepositoryCache.enter(cacheConfigurationManager); try { display("Thread " + Thread.currentThread().getName() + " START"); - provisioningService.deleteObject(ShadowType.class, accountMorganOid, null, null, task, localResult); + provisioningService.deleteObject(ShadowType.class, accountMorganOid, null, null, localTask, localResult); localResult.computeStatus(); display("Thread " + Thread.currentThread().getName() + " DONE, result", localResult); if (localResult.isSuccess()) { @@ -412,11 +417,11 @@ public void test210ParallelCreateSlow() throws Exception { // WHEN when(); + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { - OperationResult localResult = task.getResult().createSubresult("thread-" + i); - - RepositoryCache.enter(cacheConfigurationManager); + Task localTask = createTask(testName + "-thread-" + i); + OperationResult localResult = localTask.getResult(); randomDelay(CONCURRENT_TEST_MAX_START_DELAY_SLOW); logger.info("{} starting to do some work", Thread.currentThread().getName()); @@ -424,7 +429,7 @@ public void test210ParallelCreateSlow() throws Exception { ShadowType account = parseObjectType(ACCOUNT_ELIZABETH_FILE, ShadowType.class); try { - accountElizabethOid = provisioningService.addObject(account.asPrismObject(), null, null, task, localResult); + accountElizabethOid = provisioningService.addObject(account.asPrismObject(), null, null, localTask, localResult); successCounter.click(); } catch (ObjectAlreadyExistsException e) { // this is expected ... sometimes @@ -495,13 +500,16 @@ private PrismObject parallelModifyTestSlow( rememberDummyResourceWriteOperationCount(null); when(); + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { - OperationResult localResult = task.getResult().createSubresult("thread-" + i); + Task localTask = createTask(testName + "-thread-" + i); + OperationResult localResult = localTask.getResult(); RepositoryCache.enter(cacheConfigurationManager); // Playing with cache, trying to make a worst case - PrismObject shadowBefore = repositoryService.getObject(ShadowType.class, accountElizabethOid, null, localResult); + PrismObject shadowBefore = repositoryService.getObject( + ShadowType.class, accountElizabethOid, null, localResult); randomDelay(CONCURRENT_TEST_MAX_START_DELAY_SLOW); logger.info("{} starting to do some work", Thread.currentThread().getName()); @@ -509,7 +517,8 @@ private PrismObject parallelModifyTestSlow( ObjectDelta delta = deltaProducer.run(); display("ObjectDelta", delta); - provisioningService.modifyObject(ShadowType.class, accountElizabethOid, delta.getModifications(), null, null, task, localResult); + provisioningService.modifyObject(ShadowType.class, accountElizabethOid, + delta.getModifications(), null, null, localTask, localResult); localResult.computeStatus(); display("Thread " + Thread.currentThread().getName() + " DONE, result", localResult); @@ -550,10 +559,11 @@ public void test229ParallelDeleteSlow() throws Exception { // WHEN when(); - Task task = getTestTask(); + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { - OperationResult localResult = task.getResult().createSubresult("thread-" + i); + Task localTask = createTask(testName + "-thread-" + i); + OperationResult localResult = localTask.getResult(); RepositoryCache.enter(cacheConfigurationManager); // Playing with cache, trying to make a worst case @@ -564,7 +574,7 @@ public void test229ParallelDeleteSlow() throws Exception { try { display("Thread " + Thread.currentThread().getName() + " START"); - provisioningService.deleteObject(ShadowType.class, accountElizabethOid, null, null, task, localResult); + provisioningService.deleteObject(ShadowType.class, accountElizabethOid, null, null, localTask, localResult); localResult.computeStatus(); display("Thread " + Thread.currentThread().getName() + " DONE, result", localResult); if (localResult.isSuccess()) { @@ -625,11 +635,17 @@ public void test230ParallelGroupSearch() throws Exception { dummyResource.setOperationDelayRange(0); dummyResource.setSyncSearchHandlerStart(true); + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { + Task localTask = createTask(testName + "-thread-" + i); + OperationResult localResult = localTask.getResult(); + ObjectQuery query = createGroupNameQuery(GROUP_SCUM_NAME); - SearchResultList> foundObjects = provisioningService.searchObjects(ShadowType.class, query, null, task, result); + SearchResultList> foundObjects = + provisioningService.searchObjects( + ShadowType.class, query, null, localTask, localResult); assertEquals("Unexpected number of shadows found: " + foundObjects, 1, foundObjects.size()); successCounter.click(); @@ -723,6 +739,7 @@ public void test800ParallelReadAndModifyResource() throws Exception { long t0 = System.currentTimeMillis(); MutableBoolean readFinished = new MutableBoolean(); + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (threadIndex) -> { @@ -740,7 +757,7 @@ public void test800ParallelReadAndModifyResource() throws Exception { } else if (threadIndex == CONCURRENT_TEST_THREAD_COUNT_HIGH / 2) { for (int i = 0; /* neverending */ ; i++) { - Task localTask = createPlainTask("test-" + i); + Task localTask = createPlainTask(testName + "-test-thread-" + i); OperationResult testResult = provisioningService.testResource(RESOURCE_DUMMY_OID, localTask); logger.debug("PAR: TESTing " + threadIndex + "." + i); @@ -763,7 +780,7 @@ public void test800ParallelReadAndModifyResource() throws Exception { try { // TODO: why is the constant MESS_RESOURCE_ITERATIONS used for operations? for (int i = 0; i < MESS_RESOURCE_ITERATIONS; i++) { - Task localTask = createPlainTask("op-" + i); + Task localTask = createPlainTask(testName + "-op-thread-" + i); OperationResult localResult = localTask.getResult(); logger.debug("PAR: OPing " + threadIndex + "." + i); @@ -771,7 +788,7 @@ public void test800ParallelReadAndModifyResource() throws Exception { Object out = doResourceOperation(task, localResult); localResult.computeStatus(); - display("PAR: OPed " + threadIndex + "." + i + ": " + out.toString() + ": " + localResult.getStatus()); + display("PAR: OPed " + threadIndex + "." + i + ": " + out + ": " + localResult.getStatus()); if (localResult.getStatus() != OperationResultStatus.SUCCESS) { display("Failed read result", localResult); diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index 615ed3d0e9e..408d9659723 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -343,6 +343,7 @@ public void setPredefinedTestMethodTracing(PredefinedTestMethodTracing predefine /** * 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(); @@ -350,10 +351,15 @@ protected Task getTestTask() { /** * Creates new {@link Task} with operation name prefixed with {@link #contextName()}. - * For most tests this should be unnecessary and the default test-method-scoped task + * For many tests this is not necessary and the default test-method-scoped task * that can be obtained with {@link #getTestTask()} should be enough. - * Even for multi-threaded tests we may not need the whole task - instead - * {@link #createSubresult(String)} should suffice. + * If more tasks are needed this method creates plain task without customization, see + * also {@link #createTask} for customized task. + *

+ * 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 From 303516ca43e8e56cff5fd7ac34e9e0955507bd1c Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 16:34:39 +0100 Subject: [PATCH 48/55] AbstractSpringTest#startTestContext can throw exceptions --- .../com/evolveum/midpoint/test/util/AbstractSpringTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java index 26b5c1fd0e3..12c0b0b9617 100644 --- a/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java +++ b/infra/test-util/src/main/java/com/evolveum/midpoint/test/util/AbstractSpringTest.java @@ -36,7 +36,7 @@ public abstract class AbstractSpringTest extends AbstractTestNGSpringContextTest protected final Trace logger = TraceManager.getTrace(getClass()); @BeforeMethod - public void startTestContext(ITestResult testResult) { + public void startTestContext(ITestResult testResult) throws Exception { SimpleMidpointTestContext context = SimpleMidpointTestContext.create(testResult); displayTestTitle(context.getTestName()); } From 91afce8e144b667faed04a9b96bdaafb8c71df5e Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 18:15:55 +0100 Subject: [PATCH 49/55] TraceManager: removed unused LOGGER field --- .../java/com/evolveum/midpoint/util/logging/TraceManager.java | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/TraceManager.java b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/TraceManager.java index e401945094b..abe2c14d5e5 100644 --- a/infra/util/src/main/java/com/evolveum/midpoint/util/logging/TraceManager.java +++ b/infra/util/src/main/java/com/evolveum/midpoint/util/logging/TraceManager.java @@ -20,9 +20,7 @@ public class TraceManager { private static final String PERFORMANCE_ADVISOR = "PERFORMANCE_ADVISOR"; - private static final Logger LOGGER = org.slf4j.LoggerFactory.getLogger(TraceManager.class); - - public static Trace getTrace(Class clazz) { + public static Trace getTrace(Class clazz) { Logger logger = org.slf4j.LoggerFactory.getLogger(clazz); return new TraceImpl(logger); } From e2a1b86fa7fcb1298e2d06f8c70493077baf4b8f Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Mon, 9 Mar 2020 22:50:02 +0100 Subject: [PATCH 50/55] .editorconfig: no javadoc param alignment + applied to Tracer.java --- .editorconfig | 4 ++-- .../java/com/evolveum/midpoint/task/api/Tracer.java | 11 ++++------- 2 files changed, 6 insertions(+), 9 deletions(-) diff --git a/.editorconfig b/.editorconfig index e69d9ac9836..fe4cd7d9a30 100644 --- a/.editorconfig +++ b/.editorconfig @@ -108,8 +108,8 @@ ij_java_doc_add_blank_line_after_description = true ij_java_doc_add_blank_line_after_param_comments = false ij_java_doc_add_blank_line_after_return = false ij_java_doc_add_p_tag_on_empty_lines = true -ij_java_doc_align_exception_comments = true -ij_java_doc_align_param_comments = true +ij_java_doc_align_exception_comments = false +ij_java_doc_align_param_comments = false ij_java_doc_do_not_wrap_if_one_line = false ij_java_doc_enable_formatting = true ij_java_doc_enable_leading_asterisks = true diff --git a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java index f90f86afbd1..ea783cfd524 100644 --- a/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java +++ b/repo/task-api/src/main/java/com/evolveum/midpoint/task/api/Tracer.java @@ -18,16 +18,13 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.TracingProfileType; -/** - * - */ public interface Tracer { /** * Stores trace to persistent storage (usually a file in "trace" directory). * - * @param task Task containing the context information necessary e.g. to derive name of the trace file. - * @param result Result that is to be serialized and stored. + * @param task Task containing the context information necessary e.g. to derive name of the trace file. + * @param result Result that is to be serialized and stored. * @param parentResult Parent result where this operation should be recorded (if any). */ void storeTrace(Task task, OperationResult result, @Nullable OperationResult parentResult); @@ -35,8 +32,8 @@ public interface Tracer { /** * Resolves a tracing profile - i.e. replaces references to other (named) profiles with their content. * - * @throws SchemaException If the profile name cannot be resolved e.g. if the referenced profile does not exist - * or the name in ambiguous. + * @throws SchemaException If the profile name cannot be resolved e.g. if the referenced + * profile does not exist or the name in ambiguous. */ TracingProfileType resolve(TracingProfileType tracingProfile, OperationResult result) throws SchemaException; From b8858e3d4ad1596a9a74ff45d8c76f72b6c686b4 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Tue, 10 Mar 2020 01:14:39 +0100 Subject: [PATCH 51/55] admin-gui and EventHandler: typos, reformat, bit of cleanup --- .../ShadowAssociationWrapperFactoryImpl.java | 59 ++++--------------- .../prism/PrismContainerValueWrapperImpl.java | 15 +---- .../admin/roles/AbstractRoleMemberPanel.java | 14 +---- .../admin/roles/MemberOperationsHelper.java | 10 ++-- .../common/validator/EventHandler.java | 2 +- 5 files changed, 25 insertions(+), 75 deletions(-) diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java index c0026150ead..88f70276d17 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/factory/ShadowAssociationWrapperFactoryImpl.java @@ -24,23 +24,9 @@ import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; import com.evolveum.midpoint.gui.api.registry.GuiComponentRegistry; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.impl.prism.PrismContainerPanel; -import com.evolveum.midpoint.gui.impl.prism.PrismContainerValueWrapper; -import com.evolveum.midpoint.gui.impl.prism.PrismContainerWrapperImpl; -import com.evolveum.midpoint.gui.impl.prism.PrismReferenceValueWrapperImpl; -import com.evolveum.midpoint.gui.impl.prism.ShadowAssociationReferenceWrapperImpl; -import com.evolveum.midpoint.gui.impl.prism.ShadowAssociationWrapperImpl; +import com.evolveum.midpoint.gui.impl.prism.*; import com.evolveum.midpoint.model.api.ModelService; -import com.evolveum.midpoint.prism.Containerable; -import com.evolveum.midpoint.prism.ItemDefinition; -import com.evolveum.midpoint.prism.MutablePrismReferenceDefinition; -import com.evolveum.midpoint.prism.PrismContainer; -import com.evolveum.midpoint.prism.PrismContainerDefinition; -import com.evolveum.midpoint.prism.PrismContainerValue; -import com.evolveum.midpoint.prism.PrismContext; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.PrismReference; -import com.evolveum.midpoint.prism.PrismReferenceValue; +import com.evolveum.midpoint.prism.*; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.result.OperationResult; @@ -51,20 +37,13 @@ import com.evolveum.midpoint.util.logging.Trace; import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.web.component.prism.ValueStatus; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceObjectAssociationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author skublik - * */ @Component -public class ShadowAssociationWrapperFactoryImpl extends PrismContainerWrapperFactoryImpl{ +public class ShadowAssociationWrapperFactoryImpl extends PrismContainerWrapperFactoryImpl { private static final Trace LOGGER = TraceManager.getTrace(ShadowAssociationWrapperFactoryImpl.class); @@ -102,7 +81,6 @@ public PrismContainerWrapper createWrapper(PrismContainerValueWrapper pare return itemWrapper; } - protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper parent, PrismContainer childContainer, ItemStatus status) { @@ -112,10 +90,10 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p if (objectType instanceof ShadowType) { shadow = (ShadowType) objectType; } else { - throw new SchemaException("Something very strange happenned. Association contianer in the " + objectType.getClass().getSimpleName() + "?"); + throw new SchemaException("Something very strange happened. Association container in the " + objectType.getClass().getSimpleName() + "?"); } - if(shadow.getResourceRef().getOid() == null) { + if (shadow.getResourceRef().getOid() == null) { return super.createWrapper(parent, childContainer, status); } Task task = taskManager.createTaskInstance("Load resource ref"); @@ -135,7 +113,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p if (association == null || association.getDefinition() == null || (!(association.getDefinition().getCompileTimeClass().equals(ShadowAssociationType.class)) - && !(association.getDefinition().getCompileTimeClass().equals(ResourceObjectAssociationType.class)))){ + && !(association.getDefinition().getCompileTimeClass().equals(ResourceObjectAssociationType.class)))) { LOGGER.debug("Association for {} is not supported", association.getComplexTypeDefinition().getTypeClass()); return super.createWrapper(parent, childContainer, status); } @@ -175,8 +153,8 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p associationTransformed.createNewValue(), ItemStatus.ADDED == status ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED, context); - List> items = new ArrayList<>(); - for (RefinedAssociationDefinition refinedAssociationDefinition: refinedAssociationDefinitions) { + List> items = new ArrayList<>(); + for (RefinedAssociationDefinition refinedAssociationDefinition : refinedAssociationDefinitions) { MutablePrismReferenceDefinition shadowRefDef = prismContext .definitionFactory().createReferenceDefinition(refinedAssociationDefinition.getName(), ObjectReferenceType.COMPLEX_TYPE); shadowRefDef.toMutable().setMaxOccurs(-1); @@ -185,7 +163,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p ItemPath itemPath = null; for (PrismContainerValue associationValue : association.getValues()) { if (association.getDefinition().getCompileTimeClass().equals(ShadowAssociationType.class)) { - ShadowAssociationType shadowAssociation = (ShadowAssociationType)associationValue.asContainerable(); + ShadowAssociationType shadowAssociation = (ShadowAssociationType) associationValue.asContainerable(); if (shadowAssociation.getName().equals(refinedAssociationDefinition.getName())) { itemPath = associationValue.getPath(); shadowAss.add(associationValue.findReference(ShadowAssociationType.F_SHADOW_REF).getValue().clone()); @@ -206,7 +184,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p shadowAss.isEmpty() ? ItemStatus.ADDED : ItemStatus.NOT_CHANGED); item.setDisplayName(displayName); List refValues = new ArrayList(); - for(PrismReferenceValue prismValue : shadowAss.getValues()) { + for (PrismReferenceValue prismValue : shadowAss.getValues()) { PrismReferenceValueWrapperImpl refValue = new PrismReferenceValueWrapperImpl(item, prismValue, prismValue.isEmpty() ? ValueStatus.ADDED : ValueStatus.NOT_CHANGED); refValue.setEditEnabled(isEmpty(prismValue)); @@ -220,7 +198,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p refValue.setEditEnabled(true); refValues.add(refValue); } - item.getValues().addAll((Collection)refValues); + item.getValues().addAll((Collection) refValues); item.setFilter(WebComponentUtil.createAssociationShadowRefFilter(refinedAssociationDefinition, prismContext, resource.getOid())); // item.setReadOnly(true); @@ -228,7 +206,7 @@ protected PrismContainerWrapper createWrapper(PrismContainerValueWrapper p items.add(item); } shadowValueWrapper.setExpanded(true); - shadowValueWrapper.getItems().addAll((Collection)items); + shadowValueWrapper.getItems().addAll((Collection) items); associationWrapper.getValues().addAll(Arrays.asList(shadowValueWrapper)); return associationWrapper; } catch (Exception e) { @@ -243,16 +221,5 @@ private boolean isEmpty(PrismReferenceValue prismValue) { } return prismValue.isEmpty(); - - } - - private boolean isItemReadOnly(ItemDefinition def, PrismContainerValueWrapper cWrapper) { - if (cWrapper == null || cWrapper.getStatus() == ValueStatus.NOT_CHANGED) { - - return cWrapper.isReadOnly() || !def.canModify(); - } - - return cWrapper.isReadOnly() || !def.canAdd(); - } } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java index 8ce34d4807a..296d9040358 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/gui/impl/prism/PrismContainerValueWrapperImpl.java @@ -6,33 +6,24 @@ */ package com.evolveum.midpoint.gui.impl.prism; -import java.text.Collator; import java.util.ArrayList; import java.util.Collection; -import java.util.Collections; -import java.util.Comparator; import java.util.List; -import java.util.Locale; import javax.xml.namespace.QName; -import com.evolveum.midpoint.gui.api.prism.ItemStatus; import com.evolveum.midpoint.gui.api.prism.PrismObjectWrapper; import com.evolveum.midpoint.prism.*; -import com.evolveum.midpoint.prism.delta.ContainerDelta; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ItemPathType; -import org.apache.commons.collections4.CollectionUtils; import com.evolveum.midpoint.gui.api.prism.ItemWrapper; import com.evolveum.midpoint.gui.api.prism.PrismContainerWrapper; import com.evolveum.midpoint.gui.api.util.WebComponentUtil; -import com.evolveum.midpoint.gui.api.util.WebModelServiceUtils; import com.evolveum.midpoint.gui.api.util.WebPrismUtil; import com.evolveum.midpoint.prism.delta.ItemDelta; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.path.ItemPath; -import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.util.DebugUtil; import com.evolveum.midpoint.util.QNameUtil; import com.evolveum.midpoint.util.exception.SchemaException; @@ -68,7 +59,7 @@ public PrismContainerValueWrapperImpl(PrismContainerWrapper parent, PrismCont @Override public PrismContainerValue getValueToAdd() throws SchemaException { - Collection modifications = new ArrayList(); + Collection modifications = new ArrayList<>(); for (ItemWrapper itemWrapper : items) { Collection subDelta = itemWrapper.getDelta(); @@ -331,9 +322,9 @@ private ItemPath getVirtualItemPath(VirtualContainerItemSpecificationType virtua } } } catch (SchemaException e) { - //in this case we could ignroe the error. extension is single value container so this error should not happened + //in this case we could ignore the error. extension is single value container so this error should not happened // but just to be sure we won't miss if something strange happened just throw runtime error - LOGGER.error("Something unexpected happenned. Please, check your schema"); + LOGGER.error("Something unexpected happened. Please, check your schema"); throw new IllegalStateException(e.getMessage(), e); } diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java index fa0d04fe500..372024a1c0e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/AbstractRoleMemberPanel.java @@ -21,20 +21,16 @@ import com.evolveum.midpoint.model.api.AssignmentObjectRelation; import com.evolveum.midpoint.model.api.authentication.CompiledObjectCollectionView; import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.query.QueryFactory; import com.evolveum.midpoint.prism.query.builder.S_FilterEntryOrEmpty; import com.evolveum.midpoint.schema.constants.RelationTypes; -import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.exception.ConfigurationException; import com.evolveum.midpoint.web.component.MultiFunctinalButtonDto; import com.evolveum.midpoint.web.component.MultifunctionalButton; -import com.evolveum.midpoint.web.component.assignment.AssignmentsUtil; import com.evolveum.midpoint.web.component.data.column.ColumnUtils; import com.evolveum.midpoint.web.component.dialog.ConfigureTaskConfirmationPanel; -import com.evolveum.midpoint.web.component.dialog.ConfirmationPanel; import com.evolveum.midpoint.web.component.menu.cog.ButtonInlineMenuItem; import com.evolveum.midpoint.web.component.menu.cog.InlineMenuItemAction; import com.evolveum.midpoint.web.component.util.SelectableBean; @@ -86,7 +82,6 @@ import com.evolveum.midpoint.web.component.search.Search; import com.evolveum.midpoint.web.component.search.SearchFactory; import com.evolveum.midpoint.web.component.util.EnableBehaviour; -import com.evolveum.midpoint.web.component.util.SelectableBeanImpl; import com.evolveum.midpoint.web.component.util.VisibleBehaviour; import com.evolveum.midpoint.web.page.admin.configuration.component.ChooseTypePanel; import com.evolveum.midpoint.web.page.admin.dto.ObjectViewDto; @@ -642,8 +637,7 @@ protected List getSupportedRelations() { } protected void okPerformed(QName type, Collection relations, AjaxRequestTarget target) { - deleteMembersPerformed(type, scope, relations, target); - + deleteMembersPerformed(scope, relations, target); } @Override @@ -656,11 +650,9 @@ protected QName getDefaultObjectType() { return WebComponentUtil.classToQName(AbstractRoleMemberPanel.this.getPrismContext(), AbstractRoleMemberPanel.this.getDefaultObjectType()); } - }; getPageBase().showMainPopup(chooseTypePopupContent, target); - } protected void createFocusMemberPerformed(AjaxRequestTarget target) { @@ -744,14 +736,14 @@ protected boolean isFocusTypeSelectorVisible() { } } - protected void deleteMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { + protected void deleteMembersPerformed(QueryScope scope, Collection relations, AjaxRequestTarget target) { if (relations == null || relations.isEmpty()) { getSession().warn("No relation was selected. Cannot perform delete members"); target.add(this); target.add(getPageBase().getFeedbackPanel()); return; } - MemberOperationsHelper.deleteMembersPerformed(getPageBase(), scope, getActionQuery(scope, relations), type, target); + MemberOperationsHelper.deleteMembersPerformed(getPageBase(), scope, getActionQuery(scope, relations), target); } protected void unassignMembersPerformed(QName type, QueryScope scope, Collection relations, AjaxRequestTarget target) { diff --git a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java index 16f0e867599..5bebbc9d26e 100644 --- a/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java +++ b/gui/admin-gui/src/main/java/com/evolveum/midpoint/web/page/admin/roles/MemberOperationsHelper.java @@ -81,7 +81,7 @@ public static void unassignMembersPerformed(PageBas try { value.applyDefinition(def); } catch (SchemaException e) { - LoggingUtils.logUnexpectedException(LOGGER, "Can not aply definition " + def, e); + LoggingUtils.logUnexpectedException(LOGGER, "Can not apply definition " + def, e); operationalTask.getResult().recordFatalError(pageBase.createStringResource("MemberOperationsHelper.message.unassignMembersPerformed.fatalError", def).getString(), e); } expression.parameter(new ActionParameterValueType().name(ROLE_PARAMETER).value( @@ -126,16 +126,16 @@ public static void assignMembersPerformed(AbstractRoleType targetObject, ObjectQ executeMemberOperation(pageBase, operationalTask, type, query, script, null, target); } - public static void deleteMembersPerformed(PageBase pageBase, QueryScope scope, - ObjectQuery query, QName type, AjaxRequestTarget target) { + public static void deleteMembersPerformed( + PageBase pageBase, QueryScope scope, ObjectQuery query, AjaxRequestTarget target) { Task task = createRecomputeOrDeleteMembersTask(pageBase, scope, query, target, "delete", DELETE_OPERATION); if (task != null) { executeMemberOperation(pageBase, task, target); } } - public static void recomputeMembersPerformed(PageBase pageBase, QueryScope scope, - ObjectQuery query, AjaxRequestTarget target) { + public static void recomputeMembersPerformed( + PageBase pageBase, QueryScope scope, ObjectQuery query, AjaxRequestTarget target) { Task task = createRecomputeMembersTask(pageBase, scope, query, target); if (task != null) { executeMemberOperation(pageBase, task, target); diff --git a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventHandler.java b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventHandler.java index e36a8481682..69f2a0d6664 100644 --- a/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventHandler.java +++ b/infra/common/src/main/java/com/evolveum/midpoint/common/validator/EventHandler.java @@ -26,7 +26,7 @@ public interface EventHandler { /** - * Call-back called after deserializing to DOM and static schema validation but before unmarshall to JAXB. + * Call-back called after deserializing to DOM and static schema validation but before unmarshal to JAXB. * It can be used for extra DOM-based checks or transformations of the object. * * @param objectElement DOM tree parsed from file From 76737c587fc2aed25c1b79885981ae9cfad5bcb5 Mon Sep 17 00:00:00 2001 From: Richard Richter Date: Tue, 10 Mar 2020 01:15:53 +0100 Subject: [PATCH 52/55] more test cleanup, TEST_NAME removal from story, only bit left --- .../midpoint/prism/PrismInternalTestUtil.java | 2 +- .../mapping/TestMappingDynamicSimple.java | 2 +- .../mapping/TestMappingDynamicSysVar.java | 49 ++- .../model/common/mapping/TestMappingTime.java | 30 +- .../model/impl/TestRefinedSchema.java | 12 +- .../model/impl/lens/AbstractLensTest.java | 73 ++-- .../lens/TestAbstractAssignmentEvaluator.java | 4 +- .../midpoint/model/intest/TestInbounds.java | 2 +- .../manual/AbstractManualResourceTest.java | 22 +- .../model/intest/mapping/TestMapping.java | 4 +- .../model/intest/multi/TestMultiResource.java | 2 +- .../midpoint/model/intest/rbac/TestRbac.java | 4 +- .../intest/security/TestSecurityBasic.java | 2 +- .../sync/TestValidityRecomputeTask.java | 2 +- .../test/AbstractModelIntegrationTest.java | 70 +--- .../AbstractTestAssignmentApproval.java | 2 +- .../assignments/TestAssignmentsAdvanced.java | 4 +- .../impl/dummy/AbstractBasicDummyTest.java | 1 - .../provisioning/impl/dummy/TestDummy.java | 10 +- .../provisioning/impl/opendj/TestOpenDj.java | 2 +- .../test/AbstractIntegrationTest.java | 55 +-- .../quartzimpl/AbstractTaskManagerTest.java | 2 +- .../quartzimpl/TestTaskManagerContract.java | 20 +- .../midpoint/testing/sanity/TestSanity.java | 38 +- .../testing/story/AbstractStoryTest.java | 54 +-- .../story/TestConsistencyMechanism.java | 2 +- .../testing/story/TestDependencyRename.java | 30 +- .../testing/story/TestEntertainment.java | 29 +- .../testing/story/TestExistentialIssues.java | 12 +- .../story/TestInboundOutboundAssociation.java | 173 ++++------ .../testing/story/TestInducement.java | 22 +- .../testing/story/TestLimitedResources.java | 18 - .../testing/story/TestLiveSyncMadness.java | 9 - .../story/TestMachineIntelligence.java | 58 ++-- .../midpoint/testing/story/TestMapleLeaf.java | 84 +---- .../testing/story/TestMappingMadness.java | 17 - .../story/TestMisbehavingResources.java | 37 +- .../testing/story/TestNormalizers.java | 18 +- .../testing/story/TestNullAttribute.java | 64 +--- .../testing/story/TestOperationCounts.java | 27 +- .../testing/story/TestOperationPerf.java | 10 +- .../midpoint/testing/story/TestOrgSync.java | 124 ++----- .../story/TestPlentyOfAssignments.java | 22 -- .../testing/story/TestReconNullValue.java | 122 ++----- .../testing/story/TestRetirement.java | 170 ++------- .../midpoint/testing/story/TestScience.java | 16 +- .../testing/story/TestServiceAccounts.java | 97 ++---- .../story/TestServiceAccountsClassifier.java | 39 +-- .../testing/story/TestShadowsPerformance.java | 23 +- .../midpoint/testing/story/TestStrings.java | 61 +--- .../testing/story/TestUniversity.java | 83 ++--- .../midpoint/testing/story/TestUnix.java | 326 +++++++----------- .../testing/story/TestUnixTolerantAux.java | 41 +-- .../midpoint/testing/story/TestVillage.java | 203 ++++------- .../ldap/TestLdapAssociationPerformance.java | 74 ++-- .../story/ldap/TestLdapDependency.java | 106 ++---- 56 files changed, 829 insertions(+), 1756 deletions(-) diff --git a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java index d5286a82407..8014277a4b4 100644 --- a/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java +++ b/infra/prism-impl/src/test/java/com/evolveum/midpoint/prism/PrismInternalTestUtil.java @@ -369,7 +369,7 @@ public static void assertUserJackContent(PrismObject user, boolean exp if (withIncomplete) { assertTrue("Assignment is not incomplete", assContainer.isIncomplete()); } - assertEquals("Wrong assignement values", 2, assContainer.getValues().size()); + assertEquals("Wrong assignment values", 2, assContainer.getValues().size()); PrismProperty a2DescProperty = assContainer.getValue(USER_ASSIGNMENT_2_ID).findProperty(descriptionName); assertEquals("Wrong assigment 2 description", "Assignment 2", a2DescProperty.getValue().getValue()); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java index fff0f03b674..58dd11f431d 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSimple.java @@ -1167,7 +1167,7 @@ mappingFileName, getTestNameShort(), valuePolicyType, null) .build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN (1) mapping.evaluate(createTask(), opResult); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java index 3670441d781..3a5c8927980 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingDynamicSysVar.java @@ -33,8 +33,6 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.SchemaTestConstants; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; @@ -99,7 +97,7 @@ public void testScriptSystemVariablesConditionModifyObjectTrueGroovyUnrelated() "mapping-script-system-variables-condition-groovy.xml", shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -130,7 +128,7 @@ public void testScriptSystemVariablesConditionAddObjectFalse(String filename) th MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping(filename, shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -161,7 +159,7 @@ public void testScriptSystemVariablesConditionAddObjectFalseNoVal(String filenam MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping(filename, shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -191,7 +189,7 @@ public void testScriptSystemVariablesConditionAddObjectFalseNoProperty(String fi MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping(filename, shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -220,7 +218,7 @@ public void testScriptSystemVariablesConditionTrueToTrue(String filename) throws user.asObjectable().getEmployeeType().add("CAPTAIN"); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -247,7 +245,7 @@ public void testScriptSystemVariablesConditionFalseToFalse(String filename) thro MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping(filename, shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -273,7 +271,7 @@ public void testScriptSystemVariablesConditionFalseToTrue(String filename) throw MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping(filename, shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -305,7 +303,7 @@ public void testScriptSystemVariablesConditionTrueToFalse(String filename) throw user.asObjectable().getEmployeeType().add("CAPTAIN"); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -357,7 +355,7 @@ public void testScriptSystemVariablesConditionEmptyTrue(final String shortTestNa user.asObjectable().setEmployeeNumber(null); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -381,8 +379,8 @@ public void testScriptSystemVariablesConditionEmptySingleFalseToTrueFunction() t testScriptSystemVariablesConditionEmptyFalseToTrue(shortTestName, "mapping-script-system-variables-condition-empty-single-function.xml"); } - public void testScriptSystemVariablesConditionEmptyFalseToTrue(final String shortTestName, String filename) throws Exception { - + public void testScriptSystemVariablesConditionEmptyFalseToTrue( + final String shortTestName, String filename) throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, @@ -396,7 +394,7 @@ public void testScriptSystemVariablesConditionEmptyFalseToTrue(final String shor user.asObjectable().setEmployeeNumber("666"); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -448,7 +446,7 @@ public void testScriptSystemVariablesConditionEmptyFalse(final String shortTestN user.asObjectable().setEmployeeNumber("666"); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -470,7 +468,8 @@ public void testScriptSystemVariablesConditionEmptySingleTrueToFalseFunction() t testScriptSystemVariablesConditionEmptyTrueToFalse(shortTestName, "mapping-script-system-variables-condition-empty-single-function.xml"); } - public void testScriptSystemVariablesConditionEmptyTrueToFalse(final String shortTestName, String filename) throws Exception { + public void testScriptSystemVariablesConditionEmptyTrueToFalse( + final String shortTestName, String filename) throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() @@ -485,7 +484,7 @@ public void testScriptSystemVariablesConditionEmptyTrueToFalse(final String shor user.asObjectable().setEmployeeNumber(null); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -508,7 +507,7 @@ public void testNpeFalseToTrue() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping("mapping-npe.xml", shortTestName, "title", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -535,7 +534,7 @@ public void testNpeTrueToFalse() throws Exception { user.asObjectable().setAdditionalName(PrismTestUtil.createPolyStringType("Sultan of the Caribbean")); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -558,7 +557,7 @@ public void testPathEnum() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = evaluator.createMapping("mapping-path-enum.xml", shortTestName, "costCenter", delta); - OperationResult opResult = new OperationResult(shortTestName); + OperationResult opResult = createOperationResult(); // WHEN System.out.println("WHEN"); @@ -708,7 +707,7 @@ public void testEmployeeTypeDeltaAreplaceB() throws Exception { setEmployeeType(user.asObjectable(), "A"); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(getTestNameShort()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -736,7 +735,7 @@ public void testEmployeeTypeDeltaNullreplaceB() throws Exception { setEmployeeType(user.asObjectable()); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(getTestNameShort()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -764,7 +763,7 @@ public void testEmployeeTypeDeltaBreplaceB() throws Exception { setEmployeeType(user.asObjectable(), "B"); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(getTestNameShort()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -840,7 +839,7 @@ public PrismValueDeltaSetTriple> employeeTypeDeltaABA setEmployeeType(user.asObjectable(), oldVals); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(getTestNameShort()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -920,7 +919,7 @@ public PrismValueDeltaSetTriple> employeeTypeDeltaDel setEmployeeType(user.asObjectable(), oldVals); mapping.getSourceContext().recompute(); - OperationResult opResult = new OperationResult(getTestNameShort()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); diff --git a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java index 8ddd90e0c7a..c3ba0fda321 100644 --- a/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java +++ b/model/model-common/src/test/java/com/evolveum/midpoint/model/common/mapping/TestMappingTime.java @@ -30,6 +30,7 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.test.NullTaskImpl; +import com.evolveum.midpoint.test.util.OperationResultTestMixin; import com.evolveum.midpoint.tools.testng.AbstractUnitTest; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.exception.SchemaException; @@ -39,7 +40,8 @@ /** * @author Radovan Semancik */ -public class TestMappingTime extends AbstractUnitTest { +public class TestMappingTime extends AbstractUnitTest + implements OperationResultTestMixin { private static final String MAPPING_TIME_FROM_TO_FILENAME = "mapping-time-from-to.xml"; private static final String MAPPING_TIME_ACTIVATION = "mapping-time-deferred-delete.xml"; @@ -62,7 +64,7 @@ public void setupFactory() throws SAXException, IOException, SchemaException { public void testBeforeTimeFrom() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + .createModificationReplaceProperty(UserType.class, MappingTestEvaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); MappingImpl.Builder, PrismPropertyDefinition> builder = @@ -72,7 +74,7 @@ public void testBeforeTimeFrom() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -91,7 +93,7 @@ private Task createTask() { public void testBetweenTimes() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + .createModificationReplaceProperty(UserType.class, MappingTestEvaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); MappingImpl.Builder, PrismPropertyDefinition> builder = @@ -101,7 +103,7 @@ public void testBetweenTimes() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -119,7 +121,7 @@ public void testBetweenTimes() throws Exception { public void testAfterTimeTo() throws Exception { // GIVEN ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + .createModificationReplaceProperty(UserType.class, MappingTestEvaluator.USER_OLD_OID, UserType.F_EMPLOYEE_TYPE, "CAPTAIN"); MappingImpl.Builder, PrismPropertyDefinition> builder = @@ -129,7 +131,7 @@ public void testAfterTimeTo() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -157,7 +159,7 @@ public void testExistenceBefore() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -185,7 +187,7 @@ public void testExistenceAfter() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -218,7 +220,7 @@ public void testNoReferenceTime() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -238,7 +240,7 @@ public void testSetReferenceTimeBefore() throws Exception { userOld.asObjectable().getActivation().setDisableTimestamp(null); ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + .createModificationReplaceProperty(UserType.class, MappingTestEvaluator.USER_OLD_OID, ItemPath.create(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), disableTimestamp); @@ -255,7 +257,7 @@ public void testSetReferenceTimeBefore() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); @@ -275,7 +277,7 @@ public void testSetReferenceTimeAfter() throws Exception { userOld.asObjectable().getActivation().setDisableTimestamp(null); ObjectDelta delta = evaluator.getPrismContext().deltaFactory().object() - .createModificationReplaceProperty(UserType.class, evaluator.USER_OLD_OID, + .createModificationReplaceProperty(UserType.class, MappingTestEvaluator.USER_OLD_OID, ItemPath.create(UserType.F_ACTIVATION, ActivationType.F_DISABLE_TIMESTAMP), disableTimestamp); @@ -292,7 +294,7 @@ public void testSetReferenceTimeAfter() throws Exception { MappingImpl, PrismPropertyDefinition> mapping = builder.build(); - OperationResult opResult = new OperationResult(contextName()); + OperationResult opResult = createOperationResult(); // WHEN mapping.evaluate(createTask(), opResult); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java index 8b1db12081a..2b3c2cc729e 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/TestRefinedSchema.java @@ -115,7 +115,7 @@ public void test101EntitlementRefinedObjectClassesModel() { @Test public void test110DetermineObjectClassObjectClass() throws Exception { - OperationResult result = new OperationResult(getTestNameShort()); + OperationResult result = createOperationResult(); importObjectFromFile(TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE); @@ -135,7 +135,7 @@ public void test110DetermineObjectClassObjectClass() throws Exception { @Test public void test112DetermineObjectClassKindIntent() throws Exception { - OperationResult result = new OperationResult(getTestNameShort()); + OperationResult result = createOperationResult(); importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_FILE); @@ -155,7 +155,7 @@ public void test112DetermineObjectClassKindIntent() throws Exception { @Test public void test114DetermineObjectClassKindIntentObjectClass() throws Exception { - OperationResult result = new OperationResult(getTestNameShort()); + OperationResult result = createOperationResult(); importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE); @@ -175,7 +175,7 @@ public void test114DetermineObjectClassKindIntentObjectClass() throws Exception @Test public void test120DetermineObjectClassObjectClassModel() throws Exception { - OperationResult result = new OperationResult(getTestNameShort()); + OperationResult result = createOperationResult(); importObjectFromFile(TASK_RECONCILE_DUMMY_OBJECTCLASS_FILE); @@ -196,7 +196,7 @@ public void test120DetermineObjectClassObjectClassModel() throws Exception { @Test public void test122DetermineObjectClassKindIntentModel() throws Exception { - OperationResult result = new OperationResult(getTestNameShort()); + OperationResult result = createOperationResult(); importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_FILE); @@ -218,7 +218,7 @@ public void test122DetermineObjectClassKindIntentModel() throws Exception { @Test public void test124DetermineObjectClassKindIntentObjectClassModel() throws Exception { - OperationResult result = new OperationResult(getTestNameShort()); + OperationResult result = createOperationResult(); importObjectFromFile(TASK_RECONCILE_DUMMY_KIND_INTENT_OBJECTCLASS_FILE); diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/AbstractLensTest.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/AbstractLensTest.java index 7c1b51f6d87..9bf9843c602 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/AbstractLensTest.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/AbstractLensTest.java @@ -6,43 +6,38 @@ */ package com.evolveum.midpoint.model.impl.lens; +import static org.testng.AssertJUnit.*; + import java.io.File; import java.util.*; import java.util.function.Consumer; -import javax.xml.bind.JAXBException; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; import com.evolveum.midpoint.model.api.context.AssignmentPath; import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRule; import com.evolveum.midpoint.model.api.context.EvaluatedPolicyRuleTrigger; +import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; +import com.evolveum.midpoint.model.impl.lens.projector.Projector; import com.evolveum.midpoint.prism.PrismContainer; import com.evolveum.midpoint.prism.PrismContainerDefinition; import com.evolveum.midpoint.prism.delta.DeltaSetTriple; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.task.api.TaskManager; import com.evolveum.midpoint.test.TestResource; +import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; - -import com.evolveum.midpoint.model.impl.AbstractInternalModelIntegrationTest; -import com.evolveum.midpoint.model.impl.lens.projector.Projector; -import com.evolveum.midpoint.task.api.TaskManager; -import com.evolveum.midpoint.test.util.MidPointTestConstants; - -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; /** * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-model-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-model-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public abstract class AbstractLensTest extends AbstractInternalModelIntegrationTest { @@ -167,11 +162,12 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // repoAddObjectFromFile(USER_DRAKE_FILE, initResult); } - protected AssignmentType getAssignmentType(File assignmentFile) throws java.io.IOException, JAXBException, SchemaException { - AssignmentType assignmentType = unmarshallValueFromFile(assignmentFile, AssignmentType.class); + protected AssignmentType getAssignmentType(File assignmentFile) throws java.io.IOException, SchemaException { + AssignmentType assignmentType = unmarshalValueFromFile(assignmentFile, AssignmentType.class); // We need to make sure that the assignment has a parent - PrismContainerDefinition assignmentContainerDefinition = userTypeJack.asPrismObject().getDefinition().findContainerDefinition(UserType.F_ASSIGNMENT); + PrismContainerDefinition assignmentContainerDefinition = + userTypeJack.asPrismObject().getDefinition().findContainerDefinition(UserType.F_ASSIGNMENT); PrismContainer assignmentContainer = assignmentContainerDefinition.instantiate(); assignmentContainer.add(assignmentType.asPrismContainerValue().clone()); return assignmentType; @@ -204,7 +200,7 @@ void assertTargetTriggers(LensContext context, PolicyConstr display("Selected trigger", trigger); triggers.add(trigger); }); - assertEquals("Unexpected number of triggers ("+selectedConstraintKind+") in the context", expectedCount, triggers.size()); + assertEquals("Unexpected number of triggers (" + selectedConstraintKind + ") in the context", expectedCount, triggers.size()); } void assertTargetTriggers(LensContext context, PolicyConstraintKindType selectedConstraintKind, String... expectedConstraintNames) { @@ -220,7 +216,7 @@ void assertTargetTriggers(LensContext context, PolicyConstr triggersFound.add(trigger); namesFound.add(trigger.getConstraint().getName()); }); - assertEquals("Unexpected number of triggers ("+selectedConstraintKind+") in the context", expectedConstraintNames.length, triggersFound.size()); + assertEquals("Unexpected number of triggers (" + selectedConstraintKind + ") in the context", expectedConstraintNames.length, triggersFound.size()); assertEquals("Unexpected constraint names", new HashSet<>(expectedNamesList), namesFound); } @@ -234,7 +230,7 @@ void assertFocusTriggers(LensContext context, PolicyConstra display("Selected trigger", trigger); triggers.add(trigger); }); - assertEquals("Unexpected number of focus triggers ("+selectedConstraintKind+") in the context", expectedCount, triggers.size()); + assertEquals("Unexpected number of focus triggers (" + selectedConstraintKind + ") in the context", expectedCount, triggers.size()); } void assertFocusTriggers(LensContext context, PolicyConstraintKindType selectedConstraintKind, String... expectedConstraintNames) { @@ -250,7 +246,7 @@ void assertFocusTriggers(LensContext context, PolicyConstra triggersFound.add(trigger); namesFound.add(trigger.getConstraint().getName()); }); - assertEquals("Unexpected number of triggers ("+selectedConstraintKind+") in the context", expectedConstraintNames.length, triggersFound.size()); + assertEquals("Unexpected number of triggers (" + selectedConstraintKind + ") in the context", expectedConstraintNames.length, triggersFound.size()); assertEquals("Unexpected constraint names", new HashSet<>(expectedNamesList), namesFound); } @@ -264,7 +260,7 @@ protected EvaluatedPolicyRuleTrigger assertTriggeredTargetPolicyRule(LensContext display("Triggered rule", trigger); triggers.add(trigger); if (expectedConstraintKind != null) { - assertEquals("Wrong trigger constraint type in "+trigger, expectedConstraintKind, trigger.getConstraintKind()); + assertEquals("Wrong trigger constraint type in " + trigger, expectedConstraintKind, trigger.getConstraintKind()); } }); assertEquals("Unexpected number of triggered policy rules in the context", expectedCount, triggers.size()); @@ -301,7 +297,7 @@ protected EvaluatedPolicyRule getTriggeredFocusPolicyRule(LensContext context, String targetOid, Consumer handler) { forEvaluatedTargetPolicyRule(context, targetOid, rule -> { Collection> triggers = rule.getTriggers(); - for (EvaluatedPolicyRuleTrigger trigger: triggers) { + for (EvaluatedPolicyRuleTrigger trigger : triggers) { handler.accept(trigger); } }); @@ -310,7 +306,7 @@ protected void forTriggeredTargetPolicyRule(LensContext con protected void forTriggeredFocusPolicyRule(LensContext context, Consumer handler) { forEvaluatedFocusPolicyRule(context, rule -> { Collection> triggers = rule.getTriggers(); - for (EvaluatedPolicyRuleTrigger trigger: triggers) { + for (EvaluatedPolicyRuleTrigger trigger : triggers) { handler.accept(trigger); } }); @@ -319,7 +315,7 @@ protected void forTriggeredFocusPolicyRule(LensContext cont private void forEvaluatedTargetPolicyRule(LensContext context, String targetOid, Consumer handler) { //noinspection unchecked DeltaSetTriple> evaluatedAssignmentTriple = - (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); + (DeltaSetTriple) context.getEvaluatedAssignmentTriple(); evaluatedAssignmentTriple.simpleAccept(assignment -> { if (targetOid == null || assignment.getTarget() != null && targetOid.equals(assignment.getTarget().getOid())) { assignment.getAllTargetsPolicyRules().forEach(handler); @@ -330,7 +326,7 @@ private void forEvaluatedTargetPolicyRule(LensContext conte void forEvaluatedFocusPolicyRule(LensContext context, Consumer handler) { //noinspection unchecked DeltaSetTriple> evaluatedAssignmentTriple = - (DeltaSetTriple)context.getEvaluatedAssignmentTriple(); + (DeltaSetTriple) context.getEvaluatedAssignmentTriple(); evaluatedAssignmentTriple.simpleAccept(assignment -> assignment.getFocusPolicyRules().forEach(handler)); } @@ -356,20 +352,25 @@ protected void assertAssignmentPath(AssignmentPath path, String... targetOids) { for (int i = 0; i < targetOids.length; i++) { ObjectType target = path.getSegments().get(i).getTarget(); if (targetOids[i] == null) { - assertNull("Target #" + (i+1) + " should be null; it is: " + target, target); + assertNull("Target #" + (i + 1) + " should be null; it is: " + target, target); } else { - assertNotNull("Target #" + (i+1) + " should not be null", target); - assertEquals("Wrong OID in target #" + (i+1), targetOids[i], target.getOid()); + assertNotNull("Target #" + (i + 1) + " should not be null", target); + assertEquals("Wrong OID in target #" + (i + 1), targetOids[i], target.getOid()); } } } - protected void assertAssignmentPolicySituation(LensContext context, String roleOid, String... uris) { - AssignmentType assignment = findAssignmentByTargetRequired(context.getFocusContext().getObjectNew(), roleOid); - PrismAsserts.assertEqualsCollectionUnordered("Wrong assignment policy situation", assignment.getPolicySituation(), uris); + protected void assertAssignmentPolicySituation( + LensContext context, String roleOid, String... uris) { + AssignmentType assignment = findAssignmentByTargetRequired( + context.getFocusContext().getObjectNew(), roleOid); + PrismAsserts.assertEqualsCollectionUnordered( + "Wrong assignment policy situation", assignment.getPolicySituation(), uris); } - protected void assertFocusPolicySituation(LensContext context, String... uris) { - PrismAsserts.assertEqualsCollectionUnordered("Wrong focus policy situation", context.getFocusContext().getObjectNew().asObjectable().getPolicySituation(), uris); + protected void assertFocusPolicySituation( + LensContext context, String... uris) { + PrismAsserts.assertEqualsCollectionUnordered("Wrong focus policy situation", + context.getFocusContext().getObjectNew().asObjectable().getPolicySituation(), uris); } } diff --git a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java index 87ef0879626..816aee847c3 100644 --- a/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java +++ b/model/model-impl/src/test/java/com/evolveum/midpoint/model/impl/lens/TestAbstractAssignmentEvaluator.java @@ -179,7 +179,7 @@ public void test120DirectExpressionReplaceDescription() throws Exception { OperationResult result = task.getResult(); PrismObject user = userTypeJack.asPrismObject().clone(); - AssignmentType assignmentType = unmarshallValueFromFile(ASSIGNMENT_DIRECT_EXPRESSION_FILE, AssignmentType.class); + AssignmentType assignmentType = unmarshalValueFromFile(ASSIGNMENT_DIRECT_EXPRESSION_FILE, AssignmentType.class); user.asObjectable().getAssignment().add(assignmentType.clone()); ItemPath path = ItemPath.create(UserType.F_ASSIGNMENT, 123L, AssignmentType.F_DESCRIPTION); @@ -240,7 +240,7 @@ public void test130DirectExpressionReplaceDescriptionFromNull() throws Exception OperationResult result = task.getResult(); PrismObject user = userTypeJack.asPrismObject().clone(); - AssignmentType assignmentType = unmarshallValueFromFile(ASSIGNMENT_DIRECT_EXPRESSION_FILE, AssignmentType.class); + AssignmentType assignmentType = unmarshalValueFromFile(ASSIGNMENT_DIRECT_EXPRESSION_FILE, AssignmentType.class); assignmentType.setDescription(null); user.asObjectable().getAssignment().add(assignmentType.clone()); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java index c7b63870f1e..e847e7da6a1 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/TestInbounds.java @@ -110,7 +110,7 @@ public void test101ModifyUserSubtypePirate() throws Exception { /** * Switch subtype from PIRATE to BUCCANEER. This makes one condition to go false and the other to go - * true. For the same role assignement value. So nothing should be changed. + * true. For the same role assignment value. So nothing should be changed. */ @Test public void test102ModifyUserSubtypeBuccaneer() throws Exception { diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java index e7e000251e5..fadbc318e97 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/manual/AbstractManualResourceTest.java @@ -346,7 +346,7 @@ public void test014Configuration() throws Exception { PrismContainer configurationContainer = resource.findContainer(ResourceType.F_CONNECTOR_CONFIGURATION); assertNotNull("No configuration container", configurationContainer); - PrismContainerDefinition confContDef = configurationContainer.getDefinition(); + PrismContainerDefinition confContDef = configurationContainer.getDefinition(); assertNotNull("No configuration container definition", confContDef); PrismProperty propDefaultAssignee = configurationContainer.findProperty(CONF_PROPERTY_DEFAULT_ASSIGNEE_QNAME); assertNotNull("No defaultAssignee conf prop", propDefaultAssignee); @@ -1702,15 +1702,16 @@ public void test910ConcurrentRolesAssign() throws Exception { // WHEN when(); - + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { login(userAdministrator); - Task localTask = getTestTask(); + Task localTask = createTask(testName + "-thread-" + i); assignRole(USER_DRAKE_OID, getRoleOid(i), localTask, localTask.getResult()); - - }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRangeAssign()); + }, + getConcurrentTestNumberOfThreads(), + getConcurrentTestRandomStartDelayRangeAssign()); // THEN then(); @@ -1774,16 +1775,16 @@ public void test919ConcurrentRoleUnassign() throws Exception { display("user before", userBefore); assertAssignments(userBefore, getConcurrentTestNumberOfThreads()); - final long TIMEOUT = 60000L; + final long TIMEOUT = 60_000L; // WHEN when(); - + String testName = getTestNameShort(); ParallelTestThread[] threads = multithread( (i) -> { display("Thread " + Thread.currentThread().getName() + " START"); login(userAdministrator); - Task localTask = getTestTask(); + Task localTask = createTask(testName + "-thread-" + i); OperationResult localResult = localTask.getResult(); unassignRole(USER_DRAKE_OID, getRoleOid(i), localTask, localResult); @@ -1791,8 +1792,9 @@ public void test919ConcurrentRoleUnassign() throws Exception { localResult.computeStatus(); display("Thread " + Thread.currentThread().getName() + " DONE, result", localResult); - - }, getConcurrentTestNumberOfThreads(), getConcurrentTestRandomStartDelayRangeUnassign()); + }, + getConcurrentTestNumberOfThreads(), + getConcurrentTestRandomStartDelayRangeUnassign()); // THEN then(); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMapping.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMapping.java index 46fa677c7d8..6c27f506818 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMapping.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/mapping/TestMapping.java @@ -1547,7 +1547,7 @@ public void test168ModifyUserOrganization() throws Exception { } /** - * Note: red resource disables account on unsassign, does NOT delete it + * Note: red resource disables account on unassign, does NOT delete it */ @Test public void test178ModifyUserUnassignAccountRed() throws Exception { @@ -1602,7 +1602,7 @@ public void test178ModifyUserUnassignAccountRed() throws Exception { } /** - * Note: red resource disables account on unsassign, does NOT delete it + * Note: red resource disables account on unassign, does NOT delete it * So let's delete the account explicitly to make room for the following tests */ @Test diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java index 0ea5a788306..13c83574bc3 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/multi/TestMultiResource.java @@ -1180,7 +1180,7 @@ public void test300AddAndAssignRelative() throws Exception { // Add default dummy account to jack without assigning it. // In relative mode this account should shay untouched while we play with assignments and - // unsassignements of other accounts + // unassignments of other accounts PrismObject account = PrismTestUtil.parseObject(ACCOUNT_JACK_DUMMY_FILE); ObjectDelta userDelta = prismContext.deltaFactory().object() .createEmptyModifyDelta(UserType.class, USER_JACK_OID); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java index 1d0edaab98b..37bf55015a3 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/rbac/TestRbac.java @@ -1572,7 +1572,7 @@ public void test549JackUnassignRoleWannabe() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - assertNotAssignedRole(userAfter, ROLE_WANNABE_OID, result); + assertNotAssignedRole(userAfter, ROLE_WANNABE_OID); assertRoleMembershipRef(userAfter); assertDelegatedRef(userAfter); @@ -2655,7 +2655,7 @@ public void test759JackUnassignRoleOmnimanager() throws Exception { PrismObject userAfter = getUser(USER_JACK_OID); display("User jack after", userAfter); - assertNotAssignedRole(userAfter, ROLE_PROJECT_OMNINAMAGER_OID, result); + assertNotAssignedRole(userAfter, ROLE_PROJECT_OMNINAMAGER_OID); assertHasNoOrg(userAfter); } diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java index 8b148cdd5bf..23d4e398ebf 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/security/TestSecurityBasic.java @@ -2864,7 +2864,7 @@ public void test281AutzJackEndUserSecondTime() throws Exception { } private void assertCredentialsPolicy(PrismObject user) throws ObjectNotFoundException, SchemaException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - OperationResult result = new OperationResult("assertCredentialsPolicy"); + OperationResult result = createOperationResult("assertCredentialsPolicy"); CredentialsPolicyType credentialsPolicy = modelInteractionService.getCredentialsPolicy(user, null, result); result.computeStatus(); TestUtil.assertSuccess(result); diff --git a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java index 6ccb2337a2e..cc75bbd1946 100644 --- a/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java +++ b/model/model-intest/src/test/java/com/evolveum/midpoint/model/intest/sync/TestValidityRecomputeTask.java @@ -1376,7 +1376,7 @@ public void test205AccountRedElaineDisable() throws Exception { } /** - * Note: red resource disables account on unsassign, does NOT delete it. + * Note: red resource disables account on unassign, does NOT delete it. * Just the recompute trigger is set */ @Test diff --git a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java index cc2f5bfca17..d50774ae863 100644 --- a/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java +++ b/model/model-test/src/main/java/com/evolveum/midpoint/model/test/AbstractModelIntegrationTest.java @@ -164,9 +164,11 @@ public abstract class AbstractModelIntegrationTest extends AbstractIntegrationTe @Autowired protected DashboardService dashboardService; @Autowired protected ModelAuditService modelAuditService; @Autowired protected ModelPortType modelWeb; + @Autowired @Qualifier("cacheRepositoryService") protected RepositoryService repositoryService; + @Autowired @Qualifier("sqlRepositoryServiceImpl") protected RepositoryService plainRepositoryService; @@ -1558,8 +1560,8 @@ protected ObjectDelta createAssignmentDelta(Class ty String resourceOid, ShadowKindType kind, String intent, boolean add) throws SchemaException { Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(resourceOid, kind, intent, add)); - ObjectDelta userDelta = prismContext.deltaFactory().object().createModifyDelta(focusOid, modifications, type - ); + ObjectDelta userDelta = prismContext.deltaFactory().object() + .createModifyDelta(focusOid, modifications, type); return userDelta; } @@ -1599,7 +1601,7 @@ protected ModelContext previewChanges(ObjectDelta o return modelInteractionService.previewChanges(deltas, options, task, result); } - protected void assignAccountToUser( + protected void assignAccountToUser( String focusOid, String resourceOid, String intent) throws SchemaException, ObjectAlreadyExistsException, ObjectNotFoundException, ExpressionEvaluationException, CommunicationException, ConfigurationException, @@ -1749,6 +1751,7 @@ protected Collection> listAccounts( RefinedObjectClassDefinition rAccount = rSchema.getDefaultRefinedDefinition(ShadowKindType.ACCOUNT); Collection identifierDefs = rAccount.getPrimaryIdentifiers(); assert identifierDefs.size() == 1 : "Unexpected identifier set in " + resource + " refined schema: " + identifierDefs; + // TODO any assert about this unused variable? ResourceAttributeDefinition identifierDef = identifierDefs.iterator().next(); ObjectQuery query = prismContext.queryFor(ShadowType.class) .item(ShadowType.F_OBJECT_CLASS).eq(rAccount.getObjectClassDefinition().getTypeName()) @@ -1868,9 +1871,9 @@ protected ShadowAsserter assertShadow(String username, PrismObject findShadowByNameViaModel(ShadowKindType kind, String intent, String name, - PrismObject resource, Collection> options, Task task, - OperationResult result) + protected PrismObject findShadowByNameViaModel( + ShadowKindType kind, String intent, String name, PrismObject resource, + Collection> options, Task task, OperationResult result) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { RefinedResourceSchema rSchema = RefinedResourceSchemaImpl.getRefinedSchema(resource); @@ -2192,11 +2195,6 @@ protected void assertDelegatedRef(PrismObject focus, St PrismAsserts.assertSets("Wrong values in delegatedRef in " + focus, refOids, oids); } - protected void assertNotAssignedRole( - PrismObject focus, String roleOid, OperationResult result) { - MidPointAsserts.assertNotAssignedRole(focus, roleOid); - } - protected void assertNotAssignedRole(String userOid, String roleOid, OperationResult result) throws ObjectNotFoundException, SchemaException { PrismObject user = repositoryService.getObject(UserType.class, userOid, null, result); @@ -2807,42 +2805,6 @@ protected ItemPath getIcfsNameAttributePath() { } - private void assertResolvedResourceRefs(ObjectDelta delta, String desc) { - if (delta == null) { - return; - } - if (delta.isAdd()) { - assertResolvedResourceRefs(delta.getObjectToAdd(), desc); - } else if (delta.isModify()) { - ReferenceDelta referenceDelta = delta.findReferenceModification(ShadowType.F_RESOURCE_REF); - if (referenceDelta != null) { - assertResolvedResourceRefs(referenceDelta.getValuesToAdd(), "valuesToAdd in " + desc); - assertResolvedResourceRefs(referenceDelta.getValuesToDelete(), "valuesToDelete in " + desc); - assertResolvedResourceRefs(referenceDelta.getValuesToReplace(), "valuesToReplace in " + desc); - } - } - } - - private void assertResolvedResourceRefs(PrismObject shadow, String desc) { - if (shadow == null) { - return; - } - PrismReference resourceRef = shadow.findReference(ShadowType.F_RESOURCE_REF); - if (resourceRef == null) { - AssertJUnit.fail("No resourceRef in " + desc); - } - assertResolvedResourceRefs(resourceRef.getValues(), desc); - } - - private void assertResolvedResourceRefs(Collection values, String desc) { - if (values == null) { - return; - } - for (PrismReferenceValue pval : values) { - assertNotNull("resourceRef in " + desc + " does not contain object", pval.getObject()); - } - } - /** * Breaks user assignment delta in the context by inserting some empty value. This may interfere with comparing the values to * existing user values. @@ -3162,8 +3124,8 @@ protected long getTreeRunDurationMillis(String rootTaskOid) throws ObjectNotFoun .max().orElse(0); } - protected void displayOperationStatistics(String label, OperationStatsType statistics) { - display(label, StatisticsUtil.format(statistics)); + protected void displayOperationStatistics(OperationStatsType statistics) { + display("Task operation statistics for " + getTestNameShort(), StatisticsUtil.format(statistics)); } @Nullable @@ -3259,7 +3221,8 @@ public void timeout() { IntegrationTestTools.waitFor("Waiting for task " + taskOid + " start", checker, timeout, DEFAULT_TASK_SLEEP_TIME); } - protected void waitForTaskNextStart(String taskOid, boolean checkSubresult, int timeout, boolean kickTheTask) throws Exception { + protected void waitForTaskNextStart( + String taskOid, boolean checkSubresult, int timeout, boolean kickTheTask) throws Exception { OperationResult waitResult = new OperationResult(AbstractIntegrationTest.class + ".waitForTaskNextStart"); Task origTask = taskManager.getTaskWithResult(taskOid, waitResult); Long origLastRunStartTimestamp = origTask.getLastRunStartTimestamp(); @@ -5831,9 +5794,10 @@ protected TaskAsserter assertTask(TaskType task, String message) { return TaskAsserter.forTask(task.asPrismObject(), message); } - protected RepoOpAsserter createRepoOpAsserter(String details) { - PerformanceInformation repoPerformanceInformation = repositoryService.getPerformanceMonitor().getThreadLocalPerformanceInformation(); - return new RepoOpAsserter(repoPerformanceInformation, details); + protected RepoOpAsserter createRepoOpAsserter() { + PerformanceInformation repoPerformanceInformation = + repositoryService.getPerformanceMonitor().getThreadLocalPerformanceInformation(); + return new RepoOpAsserter(repoPerformanceInformation, getTestNameShort()); } protected UserAsserter assertUser(PrismObject user, String message) { diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java index 407f63dc4c7..fd9c82344aa 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/AbstractTestAssignmentApproval.java @@ -168,7 +168,7 @@ public void test020DeleteRole1Assignment() throws Exception { assertEquals("Wrong context state", ModelState.FINAL, context.getState()); result.computeStatusIfUnknown(); TestUtil.assertSuccess(result); - assertNotAssignedRole(getUser(userJackOid), getRoleOid(1), result); + assertNotAssignedRole(getUser(userJackOid), getRoleOid(1)); } /** diff --git a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java index 7e1a7842108..5f523444062 100644 --- a/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java +++ b/model/workflow-impl/src/test/java/com/evolveum/midpoint/wf/impl/assignments/TestAssignmentsAdvanced.java @@ -1226,6 +1226,8 @@ private void previewAssignRolesToJack(boolean immediate, boolean also24) throws result.tracingProfile(tracer.compileProfile(addWorkflowLogging(createModelLoggingTracingProfile()), result)); } + setGlobalTracingOverride(createModelAndProvisioningLoggingTracingProfile()); + List assignmentsToAdd = new ArrayList<>(); assignmentsToAdd.add(createAssignmentTo(roleRole21Oid, ObjectTypes.ROLE, prismContext)); assignmentsToAdd.add(createAssignmentTo(roleRole22Oid, ObjectTypes.ROLE, prismContext)); @@ -1303,7 +1305,7 @@ private void assertApprovalInfo(List inf ApprovalSchemaExecutionInformationType found = null; for (ApprovalSchemaExecutionInformationType info : infos) { assertNotNull("No taskRef", info.getCaseRef()); - PrismObject object = info.getCaseRef().asReferenceValue().getObject(); + PrismObject object = info.getCaseRef().asReferenceValue().getObject(); assertNotNull("No case in caseRef", object); CaseType aCase = (CaseType) object.asObjectable(); ApprovalContextType wfc = aCase.getApprovalContext(); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java index c99f5912652..5fb99ea76d3 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/AbstractBasicDummyTest.java @@ -837,7 +837,6 @@ public void test032ResourceAndConnectorCaching() throws Exception { @Test public void test034ResourceAndConnectorCachingForceFresh() throws Exception { - // GIVEN OperationResult result = new OperationResult(AbstractBasicDummyTest.class.getName() + ".test011ResourceAndConnectorCachingForceFresh"); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java index 5a2120dec17..01fdb1d842e 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/dummy/TestDummy.java @@ -1114,7 +1114,7 @@ public void test131AddScript() throws Exception { ShadowType account = parseObjectType(ACCOUNT_SCRIPT_FILE, ShadowType.class); display("Account before add", account); - OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); + OperationProvisioningScriptsType scriptsType = unmarshalValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); // WHEN @@ -1163,7 +1163,7 @@ public void test132ModifyScript() throws Exception { syncServiceMock.reset(); dummyResource.purgeScriptHistory(); - OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); + OperationProvisioningScriptsType scriptsType = unmarshalValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); ObjectDelta delta = prismContext.deltaFactory().object().createModificationReplaceProperty(ShadowType.class, @@ -1207,7 +1207,7 @@ public void test133ModifyScriptNoExec() throws Exception { syncServiceMock.reset(); dummyResource.purgeScriptHistory(); - OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); + OperationProvisioningScriptsType scriptsType = unmarshalValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); ObjectDelta delta = prismContext.deltaFactory().object().createModificationReplaceProperty(ShadowType.class, @@ -1246,7 +1246,7 @@ public void test134DeleteScript() throws Exception { syncServiceMock.reset(); dummyResource.purgeScriptHistory(); - OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); + OperationProvisioningScriptsType scriptsType = unmarshalValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); // WHEN @@ -1280,7 +1280,7 @@ public void test135ExecuteScript() throws Exception { syncServiceMock.reset(); dummyResource.purgeScriptHistory(); - OperationProvisioningScriptsType scriptsType = unmarshallValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); + OperationProvisioningScriptsType scriptsType = unmarshalValueFromFile(SCRIPTS_FILE, OperationProvisioningScriptsType.class); display("Provisioning scripts", PrismTestUtil.serializeAnyDataWrapped(scriptsType)); ProvisioningScriptType script = scriptsType.getScript().get(0); diff --git a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java index 14bb5b5ff9d..ad675ad07d8 100644 --- a/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java +++ b/provisioning/provisioning-impl/src/test/java/com/evolveum/midpoint/provisioning/impl/opendj/TestOpenDj.java @@ -905,7 +905,7 @@ public void test140AddAndModifyAccountJack() throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); - ShadowType object = unmarshallValueFromFile(ACCOUNT_JACK_FILE, ShadowType.class); + ShadowType object = unmarshalValueFromFile(ACCOUNT_JACK_FILE, ShadowType.class); System.out.println(SchemaDebugUtil.prettyPrint(object)); System.out.println(object.asPrismObject().debugDump()); diff --git a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java index 408d9659723..e3a40d2369e 100644 --- a/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java +++ b/repo/repo-test-util/src/main/java/com/evolveum/midpoint/test/AbstractIntegrationTest.java @@ -27,7 +27,6 @@ import javax.net.ssl.TrustManagerFactory; import javax.net.ssl.X509TrustManager; import javax.xml.bind.JAXBElement; -import javax.xml.bind.JAXBException; import javax.xml.datatype.Duration; import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; @@ -606,32 +605,35 @@ protected T parseObjectType(File file, Class clazz) th return prismObject.asObjectable(); } - protected static T unmarshallValueFromFile(File file, Class clazz) - throws IOException, JAXBException, SchemaException { + protected static T unmarshalValueFromFile(File file, Class clazz) + throws IOException, SchemaException { return PrismTestUtil.parseAnyValue(file); } - protected static T unmarshallValueFromFile(String filePath, Class clazz) - throws IOException, JAXBException, SchemaException { + protected static T unmarshalValueFromFile(String filePath, Class clazz) + throws IOException, SchemaException { return PrismTestUtil.parseAnyValue(new File(filePath)); } - protected static ObjectType unmarshallValueFromFile(String filePath) throws IOException, - JAXBException, SchemaException { - return unmarshallValueFromFile(filePath, ObjectType.class); + protected static ObjectType unmarshalValueFromFile(String filePath) + throws IOException, SchemaException { + return unmarshalValueFromFile(filePath, ObjectType.class); } - protected PrismObject addResourceFromFile(File file, String connectorType, OperationResult result) - throws JAXBException, SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { + protected PrismObject addResourceFromFile( + File file, String connectorType, OperationResult result) + throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { return addResourceFromFile(file, connectorType, false, result); } - protected PrismObject addResourceFromFile(File file, String connectorType, boolean overwrite, OperationResult result) - throws JAXBException, SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { + protected PrismObject addResourceFromFile( + File file, String connectorType, boolean overwrite, OperationResult result) + throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { return addResourceFromFile(file, Collections.singletonList(connectorType), overwrite, result); } - protected PrismObject addResourceFromFile(File file, List connectorTypes, boolean overwrite, OperationResult result) + protected PrismObject addResourceFromFile( + File file, List connectorTypes, boolean overwrite, OperationResult result) throws SchemaException, ObjectAlreadyExistsException, EncryptionException, IOException { logger.trace("addObjectFromFile: {}, connector types {}", file, connectorTypes); PrismObject resource = prismContext.parseObject(file); @@ -699,7 +701,8 @@ protected void fillInConnectorRef(PrismObject resource, String con resourceType.getConnectorRef().setType(ObjectTypes.CONNECTOR.getTypeQName()); } - protected void fillInAdditionalConnectorRef(PrismObject resource, String connectorName, String connectorType, OperationResult result) + protected void fillInAdditionalConnectorRef(PrismObject resource, + String connectorName, String connectorType, OperationResult result) throws SchemaException { ResourceType resourceType = resource.asObjectable(); PrismObject connectorPrism = findConnectorByType(connectorType, result); @@ -791,14 +794,18 @@ protected void assumeConflictResolutionAction(ConflictResolutionActionType actio } } - protected void assumeResourceAssigmentPolicy(String resourceOid, AssignmentPolicyEnforcementType policy, boolean legalize) throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { + 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 { + protected void deleteResourceAssigmentPolicy( + String oid, AssignmentPolicyEnforcementType policy, boolean legalize) + throws ObjectNotFoundException, SchemaException, ObjectAlreadyExistsException { ProjectionPolicyType syncSettings = new ProjectionPolicyType(); syncSettings.setAssignmentPolicyEnforcement(policy); syncSettings.setLegalize(legalize); @@ -809,12 +816,12 @@ protected void deleteResourceAssigmentPolicy(String oid, AssignmentPolicyEnforce Collection> modifications = new ArrayList<>(); modifications.add(deleteAssigmentEnforcement); - OperationResult result = new OperationResult("Aplying sync settings"); + OperationResult result = createOperationResult("Applying sync settings"); repositoryService.modifyObject(ResourceType.class, oid, modifications, result); - display("Aplying sync settings result", result); + display("Applying sync settings result", result); result.computeStatus(); - TestUtil.assertSuccess("Aplying sync settings failed (result)", result); + TestUtil.assertSuccess("Applying sync settings failed (result)", result); } protected AssignmentPolicyEnforcementType getAssignmentPolicyEnforcementType(SystemConfigurationType systemConfiguration) { @@ -834,13 +841,13 @@ protected void applySyncSettings(Class clazz, String oid, ItemName itemName, Pro Collection modifications = prismContext.deltaFactory().container() .createModificationReplaceContainerCollection(itemName, objectDefinition, syncSettings.asPrismContainerValue()); - OperationResult result = new OperationResult("Aplying sync settings"); + OperationResult result = new OperationResult("Applying sync settings"); repositoryService.modifyObject(clazz, oid, modifications, result); invalidateSystemObjectsCache(); - display("Aplying sync settings result", result); + display("Applying sync settings result", result); result.computeStatus(); - TestUtil.assertSuccess("Aplying sync settings failed (result)", result); + TestUtil.assertSuccess("Applying sync settings failed (result)", result); } protected void invalidateSystemObjectsCache() { @@ -2052,6 +2059,10 @@ protected TracingProfileType createPerformanceTracingProfile() { .fileNamePattern(DEFAULT_TRACING_FILENAME_PATTERN); } + protected Task createTracedTask() { + return createTracedTask(null); + } + protected Task createTracedTask(String operationName) { Task task = createTask(operationName); task.addTracingRequest(TracingRootType.CLOCKWORK_RUN); diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java index 6b3545cab30..d4b3276ba8f 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java @@ -140,7 +140,7 @@ protected PrismObject unmarshallJaxbFromFile(String fi protected PrismObject addObjectFromFile(String filePath) throws Exception { PrismObject object = unmarshallJaxbFromFile(filePath); - OperationResult result = new OperationResult(TestTaskManagerContract.class.getName() + ".addObjectFromFile"); + OperationResult result = createOperationResult("addObjectFromFile"); try { add(object, result); } catch (ObjectAlreadyExistsException e) { diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java index d78fc29ff7d..4f09c3ea90f 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java @@ -6,11 +6,10 @@ */ package com.evolveum.midpoint.task.quartzimpl; -import static com.evolveum.midpoint.util.MiscUtil.extractSingleton; - import static org.testng.AssertJUnit.*; import static com.evolveum.midpoint.test.IntegrationTestTools.waitFor; +import static com.evolveum.midpoint.util.MiscUtil.extractSingleton; import java.io.IOException; import java.util.ArrayList; @@ -19,9 +18,6 @@ import java.util.List; import javax.annotation.PostConstruct; -import com.evolveum.midpoint.prism.query.ObjectQuery; -import com.evolveum.midpoint.schema.util.TaskTypeUtil; - import org.quartz.JobExecutionContext; import org.quartz.JobKey; import org.quartz.SchedulerException; @@ -38,6 +34,7 @@ import com.evolveum.midpoint.prism.PrismPropertyDefinition; import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.query.ObjectFilter; +import com.evolveum.midpoint.prism.query.ObjectQuery; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.schema.GetOperationOptions; import com.evolveum.midpoint.schema.SelectorOptions; @@ -45,6 +42,7 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.result.OperationResultStatus; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; +import com.evolveum.midpoint.schema.util.TaskTypeUtil; import com.evolveum.midpoint.task.api.RunningTask; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskConstants; @@ -150,10 +148,12 @@ public void test004TaskBigProperty() throws Exception { // property definition ItemName shipStateQName = new ItemName("http://myself.me/schemas/whatever", "shipState"); - PrismPropertyDefinition shipStateDefinition = prismContext.getSchemaRegistry().findPropertyDefinitionByElementName(shipStateQName); + //noinspection unchecked + PrismPropertyDefinition shipStateDefinition = (PrismPropertyDefinition) + prismContext.getSchemaRegistry().findPropertyDefinitionByElementName(shipStateQName); assertNotNull("Cannot find property definition for shipState", shipStateDefinition); - PrismProperty shipStateProperty = (PrismProperty) shipStateDefinition.instantiate(); + PrismProperty shipStateProperty = shipStateDefinition.instantiate(); shipStateProperty.setRealValue(string300); task.setExtensionProperty(shipStateProperty); @@ -1314,9 +1314,9 @@ public void test999CheckingLeftovers() throws Exception { checkLeftover(leftovers, "test108", "b", result); checkLeftover(leftovers, "test110", result); checkLeftover(leftovers, "test110", "a", result); - checkLeftover(leftovers, "test120", result); - checkLeftover(leftovers, "test130", result); - checkLeftover(leftovers, "test200", result); + checkLeftover(leftovers, "test120", result); + checkLeftover(leftovers, "test130", result); + checkLeftover(leftovers, "test200", result); StringBuilder message = new StringBuilder("Leftover task(s) found:"); for (String leftover : leftovers) { diff --git a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java index 9236eef7cc3..ebbbc76f8a4 100644 --- a/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java +++ b/testing/sanity/src/test/java/com/evolveum/midpoint/testing/sanity/TestSanity.java @@ -912,7 +912,7 @@ public void test013AddOpenDjAccountToUser() throws Exception { // This is not redundant. It checks that the previous command set the policy correctly assertSyncSettingsAssignmentPolicyEnforcement(AssignmentPolicyEnforcementType.NONE); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_OPENDJ_FILENAME, ObjectDeltaType.class); // WHEN @@ -1044,7 +1044,7 @@ public void test014AddDerbyAccountToUser() throws IOException, JAXBException, Fa checkRepoDerbyResource(); assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ADD_ACCOUNT_DERBY_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -1234,7 +1234,7 @@ public void test020ModifyUser() throws Exception { assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_FULLNAME_LOCALITY_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -1328,7 +1328,7 @@ private Entry assertOpenDJAccountJack(Entry entry, String uid, String givenName) public void test022ChangeUserPassword() throws Exception { // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_PASSWORD_FILENAME, ObjectDeltaType.class); System.out.println("In modification: " + objectChange.getItemDelta().get(0).getValue().get(0)); @@ -1438,7 +1438,7 @@ public void testModifyAccountDjRoomNumber(File reqFile, String expectedVal) thro // GIVEN assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile(reqFile, ObjectDeltaType.class); + ObjectDeltaType objectChange = unmarshalValueFromFile(reqFile, ObjectDeltaType.class); objectChange.setOid(accountShadowOidOpendj); // WHEN @@ -1472,7 +1472,7 @@ public void test029ModifyAccountDjBadPath() throws Exception { // GIVEN assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_ACCOUNT_MODIFY_BAD_PATH_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidOpendj); @@ -1517,7 +1517,7 @@ public void test029ModifyAccountDjBadPath() throws Exception { @Test public void test030DisableUser() throws Exception { // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_DISABLE_FILENAME, ObjectDeltaType.class); Entry entry = openDJController.searchByUid("jack"); @@ -1627,7 +1627,7 @@ public void test030DisableUser() throws Exception { @Test public void test031EnableUser() throws Exception { // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ACTIVATION_ENABLE_FILENAME, ObjectDeltaType.class); assertNoRepoCache(); @@ -1826,7 +1826,7 @@ public void test047RenameUser() throws Exception { // GIVEN assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_NAME_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -1884,7 +1884,7 @@ public void test047RenameUser() throws Exception { public void test048ModifyUserRemoveGivenName() throws Exception { // GIVEN assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_GIVENNAME_FILENAME, ObjectDeltaType.class); displayJaxb("objectChange:", objectChange, SchemaConstants.T_OBJECT_DELTA); @@ -2005,7 +2005,7 @@ public void test100AssignRolePirate() throws Exception { assertNoRepoCache(); TestUtil.assertSuccess("addObject has failed", resultHolder.value); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -2100,7 +2100,7 @@ public void test101AccountOwnerAfterRole() throws Exception { public void test102AssignRoleCaptain() throws Exception { // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -2178,7 +2178,7 @@ public void test102AssignRoleCaptain() throws Exception { public void test103AssignRoleCaptainAgain() throws Exception { // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -2252,7 +2252,7 @@ public void test103AssignRoleCaptainAgain() throws Exception { @Test public void test105ModifyAccount() throws Exception { // GIVEN - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_ACCOUNT_MODIFY_ATTRS_FILE, ObjectDeltaType.class); objectChange.setOid(accountShadowOidGuybrushOpendj); @@ -2337,7 +2337,7 @@ public void test104AssignRoleJudge() throws Exception { Holder oidHolder = new Holder<>(); assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_JUDGE_FILENAME, ObjectDeltaType.class); try { @@ -2374,7 +2374,7 @@ public void test107UnassignRolePirate() throws Exception { // GIVEN assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_PIRATE_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -2450,7 +2450,7 @@ public void test108UnassignRoleCaptain() throws Exception { // GIVEN assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -2532,7 +2532,7 @@ public void test109UnassignRoleCaptainAgain() throws Exception { assertNoRepoCache(); - ObjectDeltaType objectChange = unmarshallValueFromFile( + ObjectDeltaType objectChange = unmarshalValueFromFile( REQUEST_USER_MODIFY_DELETE_ROLE_CAPTAIN_2_FILENAME, ObjectDeltaType.class); // WHEN ObjectTypes.USER.getTypeQName(), @@ -3115,7 +3115,7 @@ public void test420RecomputeUsers() throws Exception { // Assign role to a user, but we do this using a repository instead of model. // The role assignment will not be executed and this created an inconsistent state. - ObjectDeltaType changeAddRoleCaptain = unmarshallValueFromFile( + ObjectDeltaType changeAddRoleCaptain = unmarshalValueFromFile( REQUEST_USER_MODIFY_ADD_ROLE_CAPTAIN_1_FILENAME, ObjectDeltaType.class); Collection modifications = DeltaConvertor.toModifications(changeAddRoleCaptain.getItemDelta(), getUserDefinition()); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/AbstractStoryTest.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/AbstractStoryTest.java index 46baa1fd494..7fdfcd23ba6 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/AbstractStoryTest.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/AbstractStoryTest.java @@ -6,8 +6,24 @@ */ package com.evolveum.midpoint.testing.story; +import static org.testng.AssertJUnit.assertEquals; + +import java.io.File; +import java.io.FileNotFoundException; +import java.util.*; +import javax.xml.namespace.QName; + +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; + import com.evolveum.midpoint.model.test.AbstractModelIntegrationTest; -import com.evolveum.midpoint.prism.*; +import com.evolveum.midpoint.prism.PrismConstants; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReference; +import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.match.MatchingRule; import com.evolveum.midpoint.prism.match.MatchingRuleRegistry; import com.evolveum.midpoint.prism.path.ItemPath; @@ -23,41 +39,24 @@ import com.evolveum.midpoint.schema.statistics.RepositoryPerformanceInformationUtil; import com.evolveum.midpoint.schema.util.ObjectTypeUtil; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.caching.CachePerformanceCollector; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; - -import javax.xml.namespace.QName; - -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; - -import java.io.File; -import java.io.FileNotFoundException; -import java.util.*; /** * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class AbstractStoryTest extends AbstractModelIntegrationTest { public static final File SYSTEM_CONFIGURATION_FILE = new File(COMMON_DIR, "system-configuration.xml"); - public static final String SYSTEM_CONFIGURATION_OID = SystemObjectsType.SYSTEM_CONFIGURATION.value(); protected static final File USER_ADMINISTRATOR_FILE = new File(COMMON_DIR, "user-administrator.xml"); protected static final String USER_ADMINISTRATOR_OID = "00000000-0000-0000-0000-000000000002"; - protected static final String USER_ADMINISTRATOR_USERNAME = "administrator"; protected static final File USER_JACK_FILE = new File(COMMON_DIR, "user-jack.xml"); protected static final String USER_JACK_OID = "c0c010c0-d34d-b33f-f00d-111111111111"; @@ -65,7 +64,6 @@ public class AbstractStoryTest extends AbstractModelIntegrationTest { protected static final String USER_JACK_FULL_NAME = "Jack Sparrow"; protected static final File ROLE_SUPERUSER_FILE = new File(COMMON_DIR, "role-superuser.xml"); - protected static final String ROLE_SUPERUSER_OID = "00000000-0000-0000-0000-000000000004"; protected static final File TASK_TRIGGER_SCANNER_FILE = new File(COMMON_DIR, "task-trigger-scanner.xml"); protected static final String TASK_TRIGGER_SCANNER_OID = "00000000-0000-0000-0000-000000000007"; @@ -133,7 +131,6 @@ protected void importSystemTasks(OperationResult initResult) throws FileNotFound importObjectFromFile(TASK_VALIDITY_SCANNER_FILE, initResult); } - protected void assertUserJack(PrismObject userJack) { assertUser(userJack, USER_JACK_OID, USER_JACK_USERNAME, "Jack Sparrow", "Jack", "Sparrow"); } @@ -163,10 +160,12 @@ protected SearchResultList getWorkItems(Task task, OperationRe return modelService.searchContainers(CaseWorkItemType.class, query, null, task, result); } + @UnusedTestElement // TODO: used on demand/temporarily? then mark with suppress warning + comment protected ObjectReferenceType ort(String oid) { return ObjectTypeUtil.createObjectRef(oid, ObjectTypes.USER); } + @UnusedTestElement // TODO: used on demand/temporarily? then mark with suppress warning + comment protected PrismReferenceValue prv(String oid) { return ObjectTypeUtil.createObjectRef(oid, ObjectTypes.USER).asReferenceValue(); } @@ -200,12 +199,14 @@ protected void resetGlobalCachePerformanceCollector() { CachePerformanceCollector.INSTANCE.clear(); } - protected void dumpGlobalCachePerformanceData(String testName) { - display("Cache performance data for " + testName + " (got from cache performance collector)", CachePerformanceCollector.INSTANCE); + protected void dumpGlobalCachePerformanceData() { + display("Cache performance data for " + getTestNameShort() + + " (got from cache performance collector)", CachePerformanceCollector.INSTANCE); } - protected void dumpThreadLocalCachePerformanceData(String testName) { - dumpCachePerformanceData(testName, CachePerformanceCollector.INSTANCE.getThreadLocalPerformanceMap()); + protected void dumpThreadLocalCachePerformanceData() { + dumpCachePerformanceData(getTestNameShort(), + CachePerformanceCollector.INSTANCE.getThreadLocalPerformanceMap()); } protected void resetThreadLocalPerformanceData() { @@ -213,6 +214,7 @@ protected void resetThreadLocalPerformanceData() { CachePerformanceCollector.INSTANCE.startThreadLocalPerformanceInformationCollection(); } + @UnusedTestElement // TODO: used on demand/temporarily? then mark with suppress warning + comment protected PerformanceInformation dumpThreadLocalPerformanceData(String testName) { PerformanceInformation performanceInformation = getRepoPerformanceMonitor().getThreadLocalPerformanceInformation(); dumpRepoPerformanceData("Repo operations for " + testName, performanceInformation); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java index a111fc2782a..4db1b1c81b0 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestConsistencyMechanism.java @@ -2888,7 +2888,7 @@ private ShadowType checkPostponedAccountBasic(String accountOid, boolean modify, private Collection> createDeltas(Class type, File requestFile, String objectOid) throws IOException, SchemaException, JAXBException { try { - ObjectDeltaType objectChange = unmarshallValueFromFile(requestFile, ObjectDeltaType.class); + ObjectDeltaType objectChange = unmarshalValueFromFile(requestFile, ObjectDeltaType.class); objectChange.setOid(objectOid); ObjectDelta delta = DeltaConvertor.createObjectDelta(objectChange, prismContext); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java index 851a47337c9..62a5414ff9c 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestDependencyRename.java @@ -6,6 +6,16 @@ * and European Union Public License. See LICENSE file for details. */ +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; + +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.AfterClass; +import org.testng.annotations.Test; + import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; @@ -16,19 +26,9 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; - -import java.io.File; - -import static org.testng.AssertJUnit.assertNotNull; /** * @author Radovan Semancik - * */ @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -110,8 +110,6 @@ public void test000Sanity() throws Exception { TestUtil.assertSuccess(testResultOpenDj); } - - @Test public void test100AddUserHerman() throws Exception { Task task = getTestTask(); @@ -140,7 +138,6 @@ public void test100AddUserHerman() throws Exception { assertNoAssignments(userAfter); } - @Test public void test110HermanAssignRoleBasic() throws Exception { Task task = getTestTask(); @@ -176,8 +173,7 @@ public void test110HermanAssignRoleBasic() throws Exception { @Test public void test112HermanRename() throws Exception { - final String TEST_NAME = "test112HermanRename"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -210,8 +206,7 @@ public void test112HermanRename() throws Exception { @Test public void test120AddUserCapsizeWithBasicRole() throws Exception { - final String TEST_NAME = "test120AddUserCapsizeWithBasicRole"; - Task task = taskManager.createTaskInstance(TestDependencyRename.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = getUserDefinition().instantiate(); @@ -248,7 +243,6 @@ public void test120AddUserCapsizeWithBasicRole() throws Exception { assertShadowSecondaryIdentifier(shadowOpenDj, openDJController.getAccountDn(USER_CAPSIZE_USERNAME_FINAL), resourceOpenDjType, caseIgnoreMatchingRule); } - protected void assertUserHerman(PrismObject user, String username) { assertUser(user, username, USER_HERMAN_GIVEN_NAME, USER_HERMAN_FAMILY_NAME); } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestEntertainment.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestEntertainment.java index ce008f700cc..c401aa209fe 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestEntertainment.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestEntertainment.java @@ -6,10 +6,8 @@ */ package com.evolveum.midpoint.testing.story; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; import static org.testng.AssertJUnit.assertEquals; +import static org.testng.AssertJUnit.assertNotNull; import java.io.File; import java.util.Collection; @@ -26,21 +24,12 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestEntertainment extends AbstractStoryTest { - public static final Trace LOGGER = TraceManager.getTrace(TestEntertainment.class); - public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "entertainment"); private static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); @@ -65,7 +54,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -81,14 +70,11 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti importObjectFromFile(ROLE_META_CREATE_ORG_GROUPS_FILE); - - } @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestEntertainment.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); @@ -108,8 +94,7 @@ public void test000Sanity() throws Exception { @Test public void test001AddParentOrg() throws Exception { - final String TEST_NAME = "test001AddParentOrg"; - Task task = taskManager.createTaskInstance(TestEntertainment.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -139,8 +124,7 @@ public void test001AddParentOrg() throws Exception { @Test public void test002AddChildOrg() throws Exception { - final String TEST_NAME = "test002AddChildOrg"; - Task task = taskManager.createTaskInstance(TestEntertainment.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -199,5 +183,4 @@ private void assertIntents(ShadowType shadowType1, ShadowType shadowType2) { + intentShadow1 + ", " + intentShadow2); } } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestExistentialIssues.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestExistentialIssues.java index da29dec8b14..bc25655feac 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestExistentialIssues.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestExistentialIssues.java @@ -22,7 +22,7 @@ /** * Tests for weird activation existence mappings, delayed deletes and similar existential issues. - * + *

* MID-4564 * * @author Radovan Semancik @@ -42,8 +42,6 @@ public class TestExistentialIssues extends AbstractStoryTest { protected static final String USER_DESCARTES_USERNAME = "descartes"; protected static final String USER_DESCARTES_FULL_NAME = "René Descartes"; - protected PrismObject userAdministrator; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); @@ -59,7 +57,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100DisableUserDescartes() throws Exception { - final String TEST_NAME = "test100DisableUserDescartes"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -87,7 +84,6 @@ public void test100DisableUserDescartes() throws Exception { */ @Test public void test110DescartesAssignLazyAccount() throws Exception { - final String TEST_NAME = "test110DescartesAssignLazyAccount"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -115,7 +111,6 @@ public void test110DescartesAssignLazyAccount() throws Exception { */ @Test public void test112EnableDescartes() throws Exception { - final String TEST_NAME = "test112EnableDescartes"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -143,7 +138,6 @@ public void test112EnableDescartes() throws Exception { */ @Test public void test114DisableDescartes() throws Exception { - final String TEST_NAME = "test112EnableDescartes"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -171,7 +165,6 @@ public void test114DisableDescartes() throws Exception { */ @Test public void test116ReenableDescartes() throws Exception { - final String TEST_NAME = "test116ReenableDescartes"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -199,7 +192,6 @@ public void test116ReenableDescartes() throws Exception { */ @Test public void test120DescartesUnassignLazyAccount() throws Exception { - final String TEST_NAME = "test120DescartesUnassignLazyAccount"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -227,7 +219,6 @@ public void test120DescartesUnassignLazyAccount() throws Exception { */ @Test public void test129DeleteDescartes() throws Exception { - final String TEST_NAME = "test129DeleteDescartes"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -244,5 +235,4 @@ public void test129DeleteDescartes() throws Exception { assertNoDummyAccount(RESOURCE_DUMMY_LAZY_NAME, USER_DESCARTES_USERNAME); } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInboundOutboundAssociation.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInboundOutboundAssociation.java index caee18d43ec..d122449618d 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInboundOutboundAssociation.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInboundOutboundAssociation.java @@ -7,8 +7,6 @@ package com.evolveum.midpoint.testing.story; import java.io.File; -import java.util.function.Consumer; - import javax.xml.namespace.QName; import org.springframework.test.annotation.DirtiesContext; @@ -28,20 +26,14 @@ import com.evolveum.midpoint.test.asserter.RoleAsserter; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.util.exception.CommonException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.FocusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * Tests for bi-directional entitlement association synchronization. * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestInboundOutboundAssociation extends AbstractStoryTest { @@ -66,9 +58,6 @@ public class TestInboundOutboundAssociation extends AbstractStoryTest { public static final String SUBTYPE_GROUP = "group"; - private static final String ACCOUNT_GUYBRUSH_USERNAME = "guybrush"; - private static final String ACCOUNT_GUYBRUSH_FULLNAME = "Guybrush Threepwood"; - private static final String GROUP_PIRATES_NAME = "pirates"; private static final QName ASSOCIATION_GROUP_QNAME = new QName(MidPointConstants.NS_RI, "group"); @@ -97,7 +86,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100ImportGroupPirates() throws Exception { - final String TEST_NAME = "test100ImportGroupPirates"; DummyGroup group = new DummyGroup(GROUP_PIRATES_NAME); getDummyResourceDir().addGroup(group); @@ -114,9 +102,9 @@ public void test100ImportGroupPirates() throws Exception { RoleAsserter rolePiratesAsserter = assertRoleAfterByName(groupRoleName(GROUP_PIRATES_NAME)); rolePiratesAsserter - .assertSubtype(SUBTYPE_GROUP) - .assertIdentifier(GROUP_PIRATES_NAME) - .assignments() + .assertSubtype(SUBTYPE_GROUP) + .assertIdentifier(GROUP_PIRATES_NAME) + .assignments() .assertAssignments(1) .assertRole(ROLE_META_GROUP_OID) .end(); @@ -125,14 +113,12 @@ public void test100ImportGroupPirates() throws Exception { shadowGroupPiratesOid = rolePiratesAsserter .links() - .single() - .getOid(); + .single() + .getOid(); } @Test public void test110AssignJackDirAccount() throws Exception { - final String TEST_NAME = "test110AssignJackDirAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -147,14 +133,14 @@ public void test110AssignJackDirAccount() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(1); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertNoMembers(); + .assertNoMembers(); } /** @@ -162,8 +148,6 @@ public void test110AssignJackDirAccount() throws Exception { */ @Test public void test115Stability() throws Exception { - final String TEST_NAME = "test110AssignJackDirAccount"; - // WHEN when(); liveSyncDir(); @@ -174,26 +158,24 @@ public void test115Stability() throws Exception { display("dir after", getDummyResourceDir()); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertNoMembers(); + .assertNoMembers(); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(1); } @Test public void test120AddJackToGroupPirates() throws Exception { - final String TEST_NAME = "test120AddJackToGroupPirates"; - getDummyResourceDir().getGroupByName(GROUP_PIRATES_NAME) - .addMember(USER_JACK_USERNAME); + .addMember(USER_JACK_USERNAME); // "fake" modification of jack's account. Just to "motivate" it to be synchronized getDummyResourceDir().getAccountByUsername(USER_JACK_USERNAME) - .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "rum"); + .replaceAttributeValue(DummyResourceContoller.DUMMY_ACCOUNT_ATTRIBUTE_DRINK_NAME, "rum"); // WHEN when(); @@ -206,15 +188,15 @@ public void test120AddJackToGroupPirates() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(2) .assertRole(rolePiratesOid); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertMembers(USER_JACK_USERNAME); + .assertMembers(USER_JACK_USERNAME); } /** @@ -222,8 +204,6 @@ public void test120AddJackToGroupPirates() throws Exception { */ @Test public void test130JackUnassignRolePirates() throws Exception { - final String TEST_NAME = "test120AddJackToGroupPirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -238,21 +218,19 @@ public void test130JackUnassignRolePirates() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(1) .assertNoRole(rolePiratesOid); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertNoMembers(); + .assertNoMembers(); } @Test public void test140JackAssignRolePirates() throws Exception { - final String TEST_NAME = "test140JackAssignRolePirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -267,29 +245,26 @@ public void test140JackAssignRolePirates() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(2) .assertRole(rolePiratesOid); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertMembers(USER_JACK_USERNAME); + .assertMembers(USER_JACK_USERNAME); } /** * Unassign dir account. But there is still pirates group assignment, * therefore the account should be kept. - * @throws Exception */ @Test public void test142JackUnAssignDirAccount() throws Exception { - final String TEST_NAME = "test140JackAssignRolePirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -304,18 +279,18 @@ public void test142JackUnAssignDirAccount() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(1) .assertRole(rolePiratesOid); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertMembers(USER_JACK_USERNAME); + .assertMembers(USER_JACK_USERNAME); } /** @@ -323,8 +298,6 @@ public void test142JackUnAssignDirAccount() throws Exception { */ @Test public void test149JackUnassignRolePirates() throws Exception { - final String TEST_NAME = "test149JackUnassignRolePirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -339,19 +312,17 @@ public void test149JackUnassignRolePirates() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(0); assertNoDummyAccount(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertNoMembers(); + .assertNoMembers(); } @Test public void test150AssignJackDirAccount() throws Exception { - final String TEST_NAME = "test150AssignJackDirAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -366,20 +337,18 @@ public void test150AssignJackDirAccount() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(1); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertNoMembers(); + .assertNoMembers(); } @Test public void test152JackAssignRolePirates() throws Exception { - final String TEST_NAME = "test152JackAssignRolePirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -394,18 +363,18 @@ public void test152JackAssignRolePirates() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(2) .assertRole(rolePiratesOid); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertMembers(USER_JACK_USERNAME); + .assertMembers(USER_JACK_USERNAME); } /** @@ -413,8 +382,6 @@ public void test152JackAssignRolePirates() throws Exception { */ @Test public void test153JackUnassignRolePiratesPreview() throws Exception { - final String TEST_NAME = "test153JackUnassignRolePiratesPreview"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -422,7 +389,7 @@ public void test153JackUnassignRolePiratesPreview() throws Exception { UserType.class, USER_JACK_OID, FocusType.F_ASSIGNMENT, rolePiratesOid, RoleType.COMPLEX_TYPE, - null, (Consumer)null, false); + null, null, false); // WHEN when(); @@ -433,26 +400,26 @@ public void test153JackUnassignRolePiratesPreview() throws Exception { assertSuccess(result); assertPreviewContext(previewContext) - .projectionContexts() + .projectionContexts() + .single() + .assertNoPrimaryDelta() + .secondaryDelta() + .display() + .assertModify() + .container(ShadowType.F_ASSOCIATION) + .assertNoValuesToAdd() + .assertNoValuesToReplace() + .valuesToDelete() .single() - .assertNoPrimaryDelta() - .secondaryDelta() - .display() - .assertModify() - .container(ShadowType.F_ASSOCIATION) - .assertNoValuesToAdd() - .assertNoValuesToReplace() - .valuesToDelete() - .single() - .assertPropertyEquals(ShadowAssociationType.F_NAME, ASSOCIATION_GROUP_QNAME) - .assertRefEquals(ShadowAssociationType.F_SHADOW_REF, shadowGroupPiratesOid) - .end() - .end() - .end() - .end() - .objectNew() - .display() - .assertNoItem(ShadowType.F_ASSOCIATION); + .assertPropertyEquals(ShadowAssociationType.F_NAME, ASSOCIATION_GROUP_QNAME) + .assertRefEquals(ShadowAssociationType.F_SHADOW_REF, shadowGroupPiratesOid) + .end() + .end() + .end() + .end() + .objectNew() + .display() + .assertNoItem(ShadowType.F_ASSOCIATION); } @@ -461,8 +428,6 @@ public void test153JackUnassignRolePiratesPreview() throws Exception { */ @Test public void test154JackUnassignRolePirates() throws Exception { - final String TEST_NAME = "test154JackUnassignRolePirates"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -477,24 +442,22 @@ public void test154JackUnassignRolePirates() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(1) .assertNoRole(rolePiratesOid); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyAccountByUsername(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertNoMembers(); + .assertNoMembers(); } @Test public void test159JackUnassignDirAccount() throws Exception { - final String TEST_NAME = "test159JackUnassignDirAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -509,13 +472,13 @@ public void test159JackUnassignDirAccount() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_JACK_OID) - .assignments() + .assignments() .assertAssignments(0); assertNoDummyAccount(RESOURCE_DUMMY_DIR_NAME, USER_JACK_USERNAME); assertDummyGroupByName(RESOURCE_DUMMY_DIR_NAME, GROUP_PIRATES_NAME) - .assertNoMembers(); + .assertNoMembers(); } /** @@ -523,8 +486,6 @@ public void test159JackUnassignDirAccount() throws Exception { */ @Test public void test200MancombAssignAccount() throws Exception { - final String TEST_NAME = "test200MancombAssignAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -539,22 +500,20 @@ public void test200MancombAssignAccount() throws Exception { display("dir after", getDummyResourceDir()); assertUserAfter(USER_MANCOMB_OID) .assignments() - .assertAssignments(1); + .assertAssignments(1); assertDummyAccount(RESOURCE_DUMMY_DIR_NAME, USER_MANCOMB_USERNAME); } private String groupRoleName(String groupName) { - return "group:"+groupName; + return "group:" + groupName; } - private void liveSyncDir() throws CommonException { rerunTask(TASK_DUMMY_DIR_LIVESYNC_OID); } - private DummyResource getDummyResourceDir() { return getDummyResource(RESOURCE_DUMMY_DIR_NAME); } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInducement.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInducement.java index bc7a26d397a..b2b9754dbbc 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInducement.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestInducement.java @@ -20,16 +20,14 @@ import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - /** * testing inducements, no resources, no accounts in use. * role "processor" is assigned to user, it contains inducements for role1, role2, role3 having following conditions - * + *

* role1: no condition * role2: should not be induced when description of user equals "NO" * role3: should not be induced when user is member of role named "lock" (directly or indirectly, therefore condition runs against roleMembershipRef) */ - @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestInducement extends AbstractStoryTest { @@ -72,7 +70,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; //no resource, no extension definition //anything to check? @@ -84,8 +81,6 @@ public void test000Sanity() throws Exception { */ @Test public void test010InducementConditionsTrue() throws Exception { - final String TEST_NAME = "test010InducementConditionsTrue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -114,8 +109,6 @@ public void test010InducementConditionsTrue() throws Exception { */ @Test public void test020InducementRole2ConditionFalse() throws Exception { - final String TEST_NAME = "test020InducementRole2ConditionFalse"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -141,12 +134,10 @@ public void test020InducementRole2ConditionFalse() throws Exception { /** * assign role "lock" to user - * condition in "processor" for inducing role3 returns false if lock is contained in rolemembership + * condition in "processor" for inducing role3 returns false if lock is contained in role membership */ @Test public void test030InducementRole3ConditionFalse() throws Exception { - final String TEST_NAME = "test030InducementRole3ConditionFalse"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -155,7 +146,6 @@ public void test030InducementRole3ConditionFalse() throws Exception { // WHEN assignRole(USER_SIMPLE_OID, ROLE_LOCK_OID, task, result); - // THEN assertSuccess(result); @@ -175,8 +165,6 @@ public void test030InducementRole3ConditionFalse() throws Exception { */ @Test public void test040Recomputed() throws Exception { - final String TEST_NAME = "test040Recomputed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -204,8 +192,6 @@ public void test040Recomputed() throws Exception { */ @Test public void test050InducementRole3ConditionTrue() throws Exception { - final String TEST_NAME = "test050InducementRole3ConditionTrue"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -233,8 +219,6 @@ public void test050InducementRole3ConditionTrue() throws Exception { */ @Test public void test060Recomputed() throws Exception { - final String TEST_NAME = "test060Recomputed"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -259,8 +243,6 @@ public void test060Recomputed() throws Exception { @Test public void test070DeleteUser() throws Exception { - final String TEST_NAME = "test070DeleteUser"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLimitedResources.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLimitedResources.java index c03a84eec7f..188afa0aa8a 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLimitedResources.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLimitedResources.java @@ -67,8 +67,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -90,8 +88,6 @@ public void test000Sanity() throws Exception { @Test public void test100AssignJackAccountNoAttributeAddDelete() throws Exception { - final String TEST_NAME = "test100AssignJackAccountNoAttributeAddDelete"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -112,8 +108,6 @@ public void test100AssignJackAccountNoAttributeAddDelete() throws Exception { @Test public void test102AddJackOrganizationalUnitTreasureHunt() throws Exception { - final String TEST_NAME = "test102AddJackOrganizationalUnitTreasureHunt"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -135,8 +129,6 @@ public void test102AddJackOrganizationalUnitTreasureHunt() throws Exception { @Test public void test104AddJackOrganizationalUnitLootingSailing() throws Exception { - final String TEST_NAME = "test104AddJackOrganizationalUnitLootingSailing"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -158,8 +150,6 @@ public void test104AddJackOrganizationalUnitLootingSailing() throws Exception { @Test public void test106DeleteJackOrganizationalUnitLooting() throws Exception { - final String TEST_NAME = "test106DeleteJackOrganizationalUnitLooting"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -184,8 +174,6 @@ public void test106DeleteJackOrganizationalUnitLooting() throws Exception { */ @Test public void test108DeleteJackOrganizationalUnitTreasureHuntSailing() throws Exception { - final String TEST_NAME = "test108DeleteJackOrganizationalUnitTreasureHuntSailing"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -207,8 +195,6 @@ public void test108DeleteJackOrganizationalUnitTreasureHuntSailing() throws Exce @Test public void test109UnassignJackAccountNoAttributeAddDelete() throws Exception { - final String TEST_NAME = "test109UnassignJackAccountNoAttributeAddDelete"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -233,8 +219,6 @@ public void test109UnassignJackAccountNoAttributeAddDelete() throws Exception { */ @Test public void test110AssignJackAccountNoCreate() throws Exception { - final String TEST_NAME = "test110AssignJackAccountNoCreate"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -256,8 +240,6 @@ public void test110AssignJackAccountNoCreate() throws Exception { @Test public void test119UnassignJackAccountNoCreate() throws Exception { - final String TEST_NAME = "test119UnassignJackAccountNoCreate"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLiveSyncMadness.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLiveSyncMadness.java index d00dec1ef17..687db05ae28 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLiveSyncMadness.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestLiveSyncMadness.java @@ -21,13 +21,10 @@ import java.io.File; -import static org.testng.AssertJUnit.assertNotNull; - /** * Test for various livesync scenarios and corner cases. * * @author semancik - * */ @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -96,7 +93,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; Task task = getTestTask(); OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_HR_OID, task); @@ -112,8 +108,6 @@ public void test000Sanity() throws Exception { @Test public void test100AddHrAccountHerman() throws Exception { - final String TEST_NAME = "test100AddHrAccountHerman"; - dummyAuditService.clear(); DummyAccount newAccount = new DummyAccount(ACCOUNT_HERMAN_USERNAME); @@ -151,8 +145,6 @@ public void test100AddHrAccountHerman() throws Exception { @Test public void test110RenameHrAccountHerman() throws Exception { - final String TEST_NAME = "test110RenameHrAccountHerman"; - dummyAuditService.clear(); DummyAccount account = dummyResourceHr.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); @@ -193,7 +185,6 @@ public void test110RenameHrAccountHerman() throws Exception { */ @Test public void test112HrAccountHermanEmptyDelta() throws Exception { - final String TEST_NAME = "test112HrAccountHermanEmptyDelta"; dummyAuditService.clear(); dummyResourceHr.recordEmptyDeltaForAccountByUsername(ACCOUNT_HERMAN_USERNAME, DummyDeltaType.MODIFY); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMachineIntelligence.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMachineIntelligence.java index 97e1a8bb4ce..1503a5fa3fb 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMachineIntelligence.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMachineIntelligence.java @@ -6,20 +6,14 @@ */ package com.evolveum.midpoint.testing.story; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; +import static org.testng.AssertJUnit.*; import java.io.File; import java.io.FileInputStream; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.PrismConstants; -import com.evolveum.midpoint.prism.path.ItemPath; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -27,8 +21,10 @@ import org.testng.annotations.Test; import com.evolveum.midpoint.common.configuration.api.MidpointConfiguration; +import com.evolveum.midpoint.prism.PrismConstants; import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismTestUtil; import com.evolveum.midpoint.prism.xml.XmlTypeConverter; import com.evolveum.midpoint.schema.SearchResultList; @@ -39,23 +35,12 @@ import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.ClassPathUtil; import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.util.logging.Trace; -import com.evolveum.midpoint.util.logging.TraceManager; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; + +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMachineIntelligence extends AbstractStoryTest { - public static final Trace LOGGER = TraceManager.getTrace(TestMachineIntelligence.class); - public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "machineintelligence"); private static final File RESOURCE_HR_FILE = new File(TEST_DIR, "resource-csv-HR.xml"); @@ -73,7 +58,7 @@ public class TestMachineIntelligence extends AbstractStoryTest { private static final String NS_RESOURCE_CSV = "http://midpoint.evolveum.com/xml/ns/public/connector/icf-1/bundle/com.evolveum.polygon.connector-csv/com.evolveum.polygon.connector.csv.CsvConnector"; @Autowired - MidpointConfiguration midPointConfig; + private MidpointConfiguration midPointConfig; @Override protected File getSystemConfigurationFile() { @@ -86,11 +71,11 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti File resourceDir = new File(home, "machineintelligence"); resourceDir.mkdir(); - LOGGER.info("Start copying HR.csv from {} to {}", RESOURCE_CSV_CONTENT_FILE.getAbsolutePath(), resourceDir.getAbsolutePath()); + logger.info("Start copying HR.csv from {} to {}", RESOURCE_CSV_CONTENT_FILE.getAbsolutePath(), resourceDir.getAbsolutePath()); File desticationFile = new File(resourceDir, "HR.csv"); ClassPathUtil.copyFile(new FileInputStream(RESOURCE_CSV_CONTENT_FILE), "HR.csv", desticationFile); - if (!desticationFile.exists()){ + if (!desticationFile.exists()) { throw new SystemException("Source file for HR resource was not created"); } @@ -99,12 +84,10 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); importObjectFromFile(RESOURCE_HR_FILE); - } @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; Task task = getTestTask(); OperationResult result = task.getResult(); Object[] newRealValue = { sourceFilePath }; @@ -129,16 +112,14 @@ SchemaConstants.ICF_CONFIGURATION_PROPERTIES, new QName(NS_RESOURCE_CSV, "filePa } /** - * * WHEN: Create account in the HR, import this acount to the midPoint * THEN: User is imported to midPoint, new Organization is created, - * user is assigned to the organization, assignment is active/inactive - * according to the setting in the resource + * user is assigned to the organization, assignment is active/inactive + * according to the setting in the resource */ @Test public void test010importActiveUserRUR() throws Exception { - final String TEST_NAME = "test010importActiveUserRUR"; - Task task = taskManager.createTaskInstance(TestMachineIntelligence.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -169,8 +150,7 @@ public void test010importActiveUserRUR() throws Exception { @Test public void test011importInactiveUserChappie() throws Exception { - final String TEST_NAME = "test011importInactiveUserChappie"; - Task task = taskManager.createTaskInstance(TestMachineIntelligence.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -203,15 +183,17 @@ public void test011importInactiveUserChappie() throws Exception { } - private PrismObject assertShadowOwner(String shadowOid, String userName, String userGivenName, String userFamilyName, String userFullName, Task task, OperationResult result) throws Exception{ + private PrismObject assertShadowOwner( + String shadowOid, String userName, String userGivenName, String userFamilyName, + String userFullName, Task task, OperationResult result) throws Exception { PrismObject userRur = (PrismObject) modelService.searchShadowOwner(shadowOid, null, task, result); assertNotNull("Owner must not be null", userRur); UserType userType = userRur.asObjectable(); - assertEquals("Unexpected name in the user", PrismTestUtil.createPolyStringType(userName) , userType.getName()); - assertEquals("Unexpected givenName in the user", PrismTestUtil.createPolyStringType(userGivenName) , userType.getGivenName()); - assertEquals("Unexpected familyName in the user", PrismTestUtil.createPolyStringType(userFamilyName) , userType.getFamilyName()); - assertEquals("Unexpected fullName in the user", PrismTestUtil.createPolyStringType(userFullName) , userType.getFullName()); + assertEquals("Unexpected name in the user", PrismTestUtil.createPolyStringType(userName), userType.getName()); + assertEquals("Unexpected givenName in the user", PrismTestUtil.createPolyStringType(userGivenName), userType.getGivenName()); + assertEquals("Unexpected familyName in the user", PrismTestUtil.createPolyStringType(userFamilyName), userType.getFamilyName()); + assertEquals("Unexpected fullName in the user", PrismTestUtil.createPolyStringType(userFullName), userType.getFullName()); return userRur; } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMapleLeaf.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMapleLeaf.java index 2282610f438..0969273cba3 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMapleLeaf.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMapleLeaf.java @@ -6,21 +6,15 @@ */ package com.evolveum.midpoint.testing.story; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; +import static org.testng.Assert.*; import static org.testng.AssertJUnit.assertNotNull; import static org.testng.AssertJUnit.assertNull; import java.io.File; import java.util.Collection; import java.util.List; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.path.ItemPath; import org.apache.commons.lang3.BooleanUtils; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; @@ -33,6 +27,7 @@ import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.PrismReference; import com.evolveum.midpoint.prism.delta.ObjectDelta; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.processor.ResourceAttributeContainer; @@ -41,26 +36,15 @@ import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.xml.ns._public.common.api_types_3.ExecuteCredentialResetRequestType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.CredentialsType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.PasswordType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemConfigurationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.ProtectedStringType; -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMapleLeaf extends AbstractStoryTest { public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "mapleLeaf"); - public static final String NS_EXT = "http://midpoint.evolveum.com/xml/ns/story/mapleLeaf/ext"; - private static final File SYSTEM_CONFIGURATION_FILE = new File(TEST_DIR, "system-configuration.xml"); private static final File SECURITY_POLICY_FILE = new File(TEST_DIR, "security-policy.xml"); @@ -74,24 +58,19 @@ public class TestMapleLeaf extends AbstractStoryTest { private static final File ROLE_META_MONKEY_DONKEY = new File(TEST_DIR, "meta-role-monkey-donkey.xml"); private static final File ROLE_MAPLE_LEAF_FACULTY_LICENSE = new File(TEST_DIR, "role-maple-leaf-faculty-license.xml"); - private static final String ROLE_MAPLE_LEAF_FACULTY_LICENSE_OID = "00000000-role-meta-0000-000011112222"; private static final File ROLE_MAPLE_LEAF_FACULTY = new File(TEST_DIR, "role-maple-leaf-faculty.xml"); private static final String ROLE_MAPLE_LEAF_FACULTY_OID = "00000000-role-0000-0000-000011112222"; private static final File ROLE_MAPLE_LEAF_GRADUATE_LICENSE = new File(TEST_DIR, "role-maple-leaf-graduate-license.xml"); - private static final String ROLE_MAPLE_LEAF_GRADUATE_LICENSE_OID = "00000000-role-meta-0000-000011113333"; private static final File ROLE_MAPLE_LEAF_GRADUATE = new File(TEST_DIR, "role-maple-leaf-graduate.xml"); private static final String ROLE_MAPLE_LEAF_GRADUATE_OID = "00000000-role-0000-0000-000011113333"; private static final File OBJECT_TEMPLATE_USER = new File(TEST_DIR, "object-template-user.xml"); - private static final String OBJECT_TEMPLATE_USER_OID = "10000000-0000-0000-0000-000000000222"; - private static final String LDIF_GROUPS = TEST_DIR + "/mapleLeafGroups.ldif"; + private static final String LDIF_GROUPS = TEST_DIR + "/mapleLeafGroups.ldif"; private static final String NS_RESOURCE = "http://midpoint.evolveum.com/xml/ns/public/resource/instance-3"; - protected static final ItemPath ACTIVATION_EFFECTIVE_STATUS_PATH = SchemaConstants.PATH_ACTIVATION_EFFECTIVE_STATUS; - protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @@ -101,7 +80,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -134,8 +113,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestMapleLeaf.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); @@ -155,8 +133,6 @@ public void test000Sanity() throws Exception { @Test public void test001addUser() throws Exception { - final String TEST_NAME = "test001addUser"; - //when when(); assignAccountToUser(USER_JACK_OID, RESOURCE_OPENDJ_OID, "default"); @@ -186,8 +162,6 @@ public void test001addUser() throws Exception { @Test public void test002assignRoleSquirrel() throws Exception { - final String TEST_NAME = "test002assignRoleSquirrel"; - //when when(); assignRole(USER_JACK_OID, ROLE_SQUIRREL_OID); @@ -217,8 +191,6 @@ public void test002assignRoleSquirrel() throws Exception { @Test public void test003unassignRoleSquirrel() throws Exception { - final String TEST_NAME = "test003unassignRoleSquirrel"; - //when when(); unassignRole(USER_JACK_OID, ROLE_SQUIRREL_OID); @@ -246,11 +218,8 @@ public void test003unassignRoleSquirrel() throws Exception { assertTrue(values.contains("mcconkey"), "No mcconkey found among values"); } - @Test public void test004assignRoleMapleLeafFaculty() throws Exception { - final String TEST_NAME = "test004assignRoleMapleLeafFaculty"; - //when when(); assignRole(USER_JACK_OID, ROLE_MAPLE_LEAF_FACULTY_OID); @@ -278,19 +247,8 @@ public void test004assignRoleMapleLeafFaculty() throws Exception { } - private boolean containRoleMemebrShip(List roleMemberships, String roleId) { - for (ObjectReferenceType ref : roleMemberships) { - if (ref.getOid().equals(roleId)) { - return true; - } - } - return false; - } - @Test public void test005assignRoleMapleLeafGraduate() throws Exception { - final String TEST_NAME = "test005assignRoleMapleLeafGraduate"; - //when when(); assignRole(USER_JACK_OID, ROLE_MAPLE_LEAF_GRADUATE_OID); @@ -321,8 +279,6 @@ public void test005assignRoleMapleLeafGraduate() throws Exception { @Test public void test006unassignRoleMapleLeafFaculty() throws Exception { - final String TEST_NAME = "test006unassignRoleMapleLeafFaculty"; - //when when(); unassignRole(USER_JACK_OID, ROLE_MAPLE_LEAF_FACULTY_OID); @@ -349,13 +305,9 @@ public void test006unassignRoleMapleLeafFaculty() throws Exception { openDJController.assertUniqueMember("cn=mapleLeafGraduateLicense,ou=groups,dc=example,dc=com", "uid=jack,ou=People,dc=example,dc=com"); } - - @Test public void test100changePasswordForceChange() throws Exception { - final String TEST_NAME = "test100changePasswordForceChange"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); //given @@ -389,9 +341,9 @@ public void test100changePasswordForceChange() throws Exception { UserType userTypeAfter = userAfter.asObjectable(); CredentialsType credentials = userTypeAfter.getCredentials(); - assertNotNull("Oooops, something unexpected happenned - no credentials found in user " + userAfter, credentials); + assertNotNull("Oooops, something unexpected happened - no credentials found in user " + userAfter, credentials); PasswordType password = credentials.getPassword(); - assertNotNull("Oooops, something unexpected happenned - no password defined for user " + userAfter, password); + assertNotNull("Oooops, something unexpected happened - no password defined for user " + userAfter, password); String clearTextValue = protector.decryptString(password.getValue()); assertEquals(clearTextValue, "somenewValue", "Passwords don't match"); @@ -408,9 +360,7 @@ public void test100changePasswordForceChange() throws Exception { @Test public void test101resetPassword() throws Exception { - final String TEST_NAME = "test101resetPassword"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); openDJController.assertPassword("uid=jack,ou=People,dc=example,dc=com", "oldValue"); @@ -429,9 +379,9 @@ public void test101resetPassword() throws Exception { UserType userTypeAfter = userAfter.asObjectable(); CredentialsType credentials = userTypeAfter.getCredentials(); - assertNotNull("Oooops, something unexpected happenned - no credentials found in user " + userAfter, credentials); + assertNotNull("Oooops, something unexpected happened - no credentials found in user " + userAfter, credentials); PasswordType password = credentials.getPassword(); - assertNotNull("Oooops, something unexpected happenned - no password defined for user " + userAfter, password); + assertNotNull("Oooops, something unexpected happened - no password defined for user " + userAfter, password); String clearTextValue = protector.decryptString(password.getValue()); assertEquals(clearTextValue, "123passwd456", "Passwords don't match"); @@ -442,9 +392,7 @@ public void test101resetPassword() throws Exception { @Test public void test200setArchivedAdministrativeStatus() throws Exception { - final String TEST_NAME = "test200setArchivedAdministrativeStatus"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); modifyUserReplace(USER_JACK_OID, ACTIVATION_ADMINISTRATIVE_STATUS_PATH, null, task, result, ActivationStatusType.ARCHIVED); @@ -461,9 +409,7 @@ public void test200setArchivedAdministrativeStatus() throws Exception { @Test public void test201SetUndefinedAdministrativeStatus() throws Exception { - final String TEST_NAME = "test201SetUndefinedAdministrativeStatus"; - - Task task = taskManager.createTaskInstance(TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); //WHEN diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMappingMadness.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMappingMadness.java index 3498d4e043d..7c19b8bd1ef 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMappingMadness.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMappingMadness.java @@ -82,8 +82,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti */ @Test public void test100AssignJackDummyAccounts() throws Exception { - final String TEST_NAME = "test100AssignJackDummyAccounts"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -111,8 +109,6 @@ public void test100AssignJackDummyAccounts() throws Exception { */ @Test public void test105ModifyJackTitleCaptain() throws Exception { - final String TEST_NAME = "test105ModifyJackTitleCaptain"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -183,8 +179,6 @@ public void test105ModifyJackTitleCaptain() throws Exception { */ @Test public void test110ModifyJackTitleWhatever() throws Exception { - final String TEST_NAME = "test110ModifyJackTitleWhatever"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -256,8 +250,6 @@ private void assertNoAttributes(DummyAccountAsserter asserter) { */ @Test public void test112ReconcileJackWhatever() throws Exception { - final String TEST_NAME = "test112ReconcileJackWhatever"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -311,8 +303,6 @@ public void test112ReconcileJackWhatever() throws Exception { */ @Test public void test120MadJack() throws Exception { - final String TEST_NAME = "test120MadJack"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -349,8 +339,6 @@ public void test120MadJack() throws Exception { */ @Test public void test130ModifyJackTitleWhateverLower() throws Exception { - final String TEST_NAME = "test130ModifyJackTitleWhateverLower"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -379,8 +367,6 @@ public void test130ModifyJackTitleWhateverLower() throws Exception { */ @Test public void test140ModifyJackTitleEmpty() throws Exception { - final String TEST_NAME = "test140ModifyJackTitleEmpty"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -414,8 +400,6 @@ public void test140ModifyJackTitleEmpty() throws Exception { @Test public void test199UnassignJackDummyAccount() throws Exception { - final String TEST_NAME = "test199UnassignJackDummyAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -505,5 +489,4 @@ private String locationize(String title) { private String drinkize(String title) { return "Drink like a " + title; } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMisbehavingResources.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMisbehavingResources.java index ebc1092b601..68cb4dd0950 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMisbehavingResources.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestMisbehavingResources.java @@ -6,14 +6,6 @@ */ package com.evolveum.midpoint.testing.story; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; - import java.io.File; import org.springframework.test.annotation.DirtiesContext; @@ -30,9 +22,8 @@ * Test for various resource-side errors, strange situations, timeouts * * @author semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestMisbehavingResources extends AbstractStoryTest { @@ -52,8 +43,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010SanityAssignJackDummyAccount() throws Exception { - final String TEST_NAME = "test010SanityAssignJackDummyAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -67,13 +56,11 @@ public void test010SanityAssignJackDummyAccount() throws Exception { assertSuccess(result); assertDummyAccountByUsername(null, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); } @Test public void test019SanityUnassignJackDummyAccount() throws Exception { - final String TEST_NAME = "test010SanityAssignJackDummyAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -94,8 +81,6 @@ public void test019SanityUnassignJackDummyAccount() throws Exception { */ @Test public void test100AssignJackDummyAccountTimeout() throws Exception { - final String TEST_NAME = "test100AssignJackDummyAccountTimeout"; - getDummyResource().setOperationDelayOffset(3000); Task task = getTestTask(); @@ -114,9 +99,7 @@ public void test100AssignJackDummyAccountTimeout() throws Exception { } @Test - public void test102AssignJackDummyAccounRetry() throws Exception { - final String TEST_NAME = "test102AssignJackDummyAccounRetry"; - + public void test102AssignJackDummyAccountRetry() throws Exception { getDummyResource().setOperationDelayOffset(0); clockForward("P1D"); @@ -133,7 +116,7 @@ public void test102AssignJackDummyAccounRetry() throws Exception { assertSuccess(result); assertDummyAccountByUsername(null, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME); + .assertFullName(USER_JACK_FULL_NAME); } /** @@ -141,8 +124,6 @@ public void test102AssignJackDummyAccounRetry() throws Exception { */ @Test public void test110ModifyJackDummyAccountTimeout() throws Exception { - final String TEST_NAME = "test110ModifyJackDummyAccountTimeout"; - getDummyResource().setOperationDelayOffset(3000); Task task = getTestTask(); @@ -158,14 +139,12 @@ public void test110ModifyJackDummyAccountTimeout() throws Exception { assertInProgress(result); assertDummyAccountByUsername(null, USER_JACK_USERNAME) - // operation timed out, data not updated - .assertFullName(USER_JACK_FULL_NAME); + // operation timed out, data not updated + .assertFullName(USER_JACK_FULL_NAME); } @Test - public void test112ModifyJackDummyAccounRetry() throws Exception { - final String TEST_NAME = "test112ModifyJackDummyAccounRetry"; - + public void test112ModifyJackDummyAccountRetry() throws Exception { getDummyResource().setOperationDelayOffset(0); clockForward("P1D"); @@ -182,6 +161,6 @@ public void test112ModifyJackDummyAccounRetry() throws Exception { assertSuccess(result); assertDummyAccountByUsername(null, USER_JACK_USERNAME) - .assertFullName(USER_JACK_FULL_NAME_CAPTAIN); + .assertFullName(USER_JACK_FULL_NAME_CAPTAIN); } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNormalizers.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNormalizers.java index 1b2ffc68d07..c21f6ae4ba7 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNormalizers.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNormalizers.java @@ -6,14 +6,11 @@ * and European Union Public License. See LICENSE file for details. */ -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.path.ItemName; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -23,18 +20,17 @@ import com.evolveum.midpoint.prism.PrismObject; import com.evolveum.midpoint.prism.PrismProperty; import com.evolveum.midpoint.prism.impl.polystring.Ascii7PolyStringNormalizer; +import com.evolveum.midpoint.prism.path.ItemName; import com.evolveum.midpoint.prism.polystring.PolyString; import com.evolveum.midpoint.prism.polystring.PolyStringNormalizer; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SystemObjectsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * @author Radovan Semancik - * */ @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -43,7 +39,6 @@ public class TestNormalizers extends AbstractModelIntegrationTest { public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "normalizers"); public static final File SYSTEM_CONFIGURATION_NORMALIZER_ASCII7_FILE = new File(TEST_DIR, "system-configuration-normalizer-ascii7.xml"); - public static final String SYSTEM_CONFIGURATION_NORMALIZER_ASCII7_OID = SystemObjectsType.SYSTEM_CONFIGURATION.value(); protected static final File USER_TELEKE_FILE = new File(TEST_DIR, "user-teleke.xml"); protected static final String USER_TELEKE_OID = "e1b0b0a4-17c6-11e8-bfc9-efaa710b614a"; @@ -77,16 +72,13 @@ protected File getSystemConfigurationFile() { @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - PolyStringNormalizer prismNormalizer = prismContext.getDefaultPolyStringNormalizer(); - assertTrue("Wrong normalizer class, expected Ascii7PolyStringNormalizer, but was "+prismNormalizer.getClass(), + assertTrue("Wrong normalizer class, expected Ascii7PolyStringNormalizer, but was " + prismNormalizer.getClass(), prismNormalizer instanceof Ascii7PolyStringNormalizer); } @Test public void test100AddUserJack() throws Exception { - final String TEST_NAME = "test100AddUserJack"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -106,7 +98,6 @@ public void test100AddUserJack() throws Exception { @Test public void test110AddUserTeleke() throws Exception { - final String TEST_NAME = "test110AddUserTeleke"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -129,7 +120,8 @@ public void test110AddUserTeleke() throws Exception { private void assertPolyString(PrismObject user, QName propName, String expectedOrig, String expectedNorm) { PrismProperty prop = user.findProperty(ItemName.fromQName(propName)); PolyString polyString = prop.getRealValue(); - assertEquals("Wrong user "+propName.getLocalPart()+".orig", expectedOrig, polyString.getOrig()); + assertNotNull(polyString); + assertEquals("Wrong user " + propName.getLocalPart() + ".orig", expectedOrig, polyString.getOrig()); assertEquals("Wrong user \"+propName.getLocalPart()+\".norm", expectedNorm, polyString.getNorm()); } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNullAttribute.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNullAttribute.java index 3dc48c61c9f..0d8b179f746 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNullAttribute.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestNullAttribute.java @@ -8,11 +8,8 @@ import java.io.File; import java.util.Collection; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.*; -import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -20,10 +17,12 @@ import com.evolveum.icf.dummy.resource.DummyObjectClass; import com.evolveum.icf.dummy.resource.DummyResource; -import com.evolveum.midpoint.model.impl.sync.ReconciliationTaskHandler; +import com.evolveum.midpoint.prism.PrismContainer; +import com.evolveum.midpoint.prism.PrismContainerDefinition; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismObjectDefinition; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismAsserts; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; @@ -31,13 +30,7 @@ import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; - +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -50,15 +43,12 @@ public class TestNullAttribute extends AbstractStoryTest { protected static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); //see - protected static final String RESOURCE_DUMMY_ID = "DUMMY"; protected static final String RESOURCE_DUMMY_OID = "10000000-0000-0000-0000-000000000001"; - protected static final String RESOURCE_DUMMY_NAMESPACE = MidPointConstants.NS_RI; private static final String DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME = "fullname"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_SHIP = "ship"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_WEAPON = "weapon"; - public static final File ORG_TOP_FILE = new File(TEST_DIR, "org-top.xml"); public static final String ORG_TOP_OID = "00000000-8888-6666-0000-100000000001"; public static final File ROLE_ACCOUNTONLY_FILE = new File(TEST_DIR, "role-accountonly.xml"); @@ -70,19 +60,14 @@ public class TestNullAttribute extends AbstractStoryTest { public static final File USER_SMACK_FILE = new File(TEST_DIR, "user-smack.xml"); public static final String USER_SMACK_OID = "c0c010c0-d34d-b33f-f00d-111111111112"; - @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; - protected static DummyResource dummyResource; protected static DummyResourceContoller dummyResourceCtl; - protected ResourceType resourceDummyType; protected PrismObject resourceDummy; - @Override public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - // Resources //default instance, no instance id //when id is set it is required to be present in resource.xml (I guess) @@ -103,28 +88,25 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // assumeAssignmentPolicy(AssignmentPolicyEnforcementType.FULL); - // Object Templates importObjectFromFile(OBJECT_TEMPLATE_USER_FILE, initResult); setDefaultUserTemplate(OBJECT_TEMPLATE_USER_OID); - // Role importObjectFromFile(ROLE_ACCOUNTONLY_FILE, initResult); importObjectFromFile(ROLE_SHIPNWEAPON_FILE, initResult); PrismObject rolesw = getRole(ROLE_SHIPNWEAPON_OID); - display("role shipNWeapon initial", rolesw); + display("role shipNWeapon initial", rolesw); //User - importObjectFromFile(USER_SMACK_FILE, initResult); + importObjectFromFile(USER_SMACK_FILE, initResult); } @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestNullAttribute.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResult = modelService.testResource(RESOURCE_DUMMY_OID, task); TestUtil.assertSuccess(testResult); @@ -135,7 +117,6 @@ public void test000Sanity() throws Exception { PrismAsserts.assertPropertyDefinition(userExtensionDef, new QName(NS_PIRACY, "ship"), DOMUtil.XSD_STRING, 0, 1); - } /** @@ -144,8 +125,6 @@ public void test000Sanity() throws Exception { */ @Test public void test010UserSmackAssignAccountOnlyRole() throws Exception { - final String TEST_NAME = "test010UserSmackAssignAccountOnlyRole"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -173,11 +152,10 @@ public void test010UserSmackAssignAccountOnlyRole() throws Exception { PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("accountModel jack after role account only assignment", accountModel); - PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath( DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME),"Smack Sparrow"); + PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME), "Smack Sparrow"); PrismAsserts.assertNoItem(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_SHIP)); PrismAsserts.assertNoItem(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_WEAPON)); - } /** @@ -187,23 +165,20 @@ public void test010UserSmackAssignAccountOnlyRole() throws Exception { */ @Test public void test020UserSmackSetAttribute() throws Exception { - final String TEST_NAME = "test020UserSmackSetAttribute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); PrismObject smack = getUser(USER_SMACK_OID); - display("smack initial: "+smack.debugDump()); + display("smack initial: " + smack.debugDump()); - - // WHEN + // WHEN @SuppressWarnings("unchecked, raw") Collection> deltas = (Collection) prismContext.deltaFor(UserType.class) - .item(UserType.F_EXTENSION, new QName(NS_PIRACY, "ship")).add("Black Pearl") - .asObjectDeltas(USER_SMACK_OID); + .item(UserType.F_EXTENSION, new QName(NS_PIRACY, "ship")).add("Black Pearl") + .asObjectDeltas(USER_SMACK_OID); modelService.executeChanges(deltas, null, task, result); // THEN @@ -225,8 +200,8 @@ public void test020UserSmackSetAttribute() throws Exception { PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("accountModel jack after role shipnweapon assignment", accountModel); - PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath( DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME),"Smack Sparrow"); - PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath( DUMMY_ACCOUNT_ATTRIBUTE_SHIP),"Black Pearl"); + PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME), "Smack Sparrow"); + PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_SHIP), "Black Pearl"); // weapon is not in user's extension (MID-3326) //PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_WEAPON),"pistol"); @@ -240,20 +215,17 @@ public void test020UserSmackSetAttribute() throws Exception { */ @Test // MID-3325 public void test030UserSmackRemoveAttribute() throws Exception { - final String TEST_NAME = "test030UserSmackRemoveAttribute"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); - //TODO: best way to set extension properties? PrismObject userBefore = getUser(USER_SMACK_OID); display("User before", userBefore); PrismObject userNewPrism = userBefore.clone(); prismContext.adopt(userNewPrism); - if (userNewPrism.getExtension()==null)userNewPrism.createExtension(); + if (userNewPrism.getExtension() == null) { userNewPrism.createExtension(); } PrismContainer ext = userNewPrism.getExtension(); ext.setPropertyRealValue(PIRACY_SHIP_QNAME, null); @@ -266,7 +238,6 @@ public void test030UserSmackRemoveAttribute() throws Exception { when(); modelService.executeChanges(deltas, null, task, result); - // THEN then(); assertSuccess(result); @@ -287,11 +258,10 @@ public void test030UserSmackRemoveAttribute() throws Exception { PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("accountModel jack after attribute deletion", accountModel); - PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath( DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME),"Smack Sparrow"); + PrismAsserts.assertPropertyValue(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_FULLNAME), "Smack Sparrow"); PrismAsserts.assertNoItem(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_WEAPON)); PrismAsserts.assertNoItem(accountModel, dummyResourceCtl.getAttributePath(DUMMY_ACCOUNT_ATTRIBUTE_SHIP)); - } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationCounts.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationCounts.java index e6311798ce6..4488e935166 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationCounts.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationCounts.java @@ -59,13 +59,10 @@ public class TestOperationCounts extends AbstractStoryTest { private static final String RESOURCE_DUMMY_THREE_OID = "f0c6cff1-30f6-46ca-b5a1-88c2dc47862c"; private static final File ROLE_ONE_FILE = new File(TEST_DIR, "role-one.xml"); - private static final String ROLE_ONE_OID = "369d1192-cb12-4cf9-90ea-0111895e9cb5"; private static final File ROLE_TWO_FILE = new File(TEST_DIR, "role-two.xml"); - private static final String ROLE_TWO_OID = "8a1e3f58-1fb8-451e-a251-126385ddfa0a"; private static final File ROLE_THREE_FILE = new File(TEST_DIR, "role-three.xml"); - private static final String ROLE_THREE_OID = "ce741b1a-0181-4c99-aaad-3d3a5f9eb48b"; private static final File USER_ALICE_FILE = new File(TEST_DIR, "user-alice.xml"); private static final String USER_ALICE_OID = "84851118-7579-46aa-a1c7-5b22eec1e443"; @@ -111,8 +108,7 @@ protected void importSystemTasks(OperationResult initResult) { @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestOperationCounts.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultOne = modelService.testResource(RESOURCE_DUMMY_ONE_OID, task); TestUtil.assertSuccess(testResultOne); @@ -124,8 +120,7 @@ public void test000Sanity() throws Exception { @Test public void test100AddAlice() throws Exception { - final String TEST_NAME = "test100AddAlice"; - Task task = createTracedTask(TEST_NAME); + Task task = createTracedTask(); OperationResult result = task.getResult(); // GIVEN @@ -141,8 +136,8 @@ public void test100AddAlice() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - RepoOpAsserter repoOpAsserter = createRepoOpAsserter(TEST_NAME).display(); - dumpThreadLocalCachePerformanceData(TEST_NAME); + RepoOpAsserter repoOpAsserter = createRepoOpAsserter().display(); + dumpThreadLocalCachePerformanceData(); assertUser(USER_ALICE_OID, "alice") .assertFullName("Alice White") @@ -171,8 +166,7 @@ public void test100AddAlice() throws Exception { // Some objects should be cached now @Test public void test110AddBob() throws Exception { - final String TEST_NAME = "test110AddBob"; - Task task = createTracedTask(TEST_NAME); + Task task = createTracedTask(); OperationResult result = task.getResult(); // GIVEN @@ -188,8 +182,8 @@ public void test110AddBob() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - RepoOpAsserter repoOpAsserter = createRepoOpAsserter(TEST_NAME).display(); - dumpThreadLocalCachePerformanceData(TEST_NAME); + RepoOpAsserter repoOpAsserter = createRepoOpAsserter().display(); + dumpThreadLocalCachePerformanceData(); assertUser(USER_BOB_OID, "bob") .assertFullName("Bob Black") @@ -215,8 +209,7 @@ public void test110AddBob() throws Exception { @Test public void test120ModifyBob() throws Exception { - final String TEST_NAME = "test120ModifyBob"; - Task task = createTracedTask(TEST_NAME); + Task task = createTracedTask(); OperationResult result = task.getResult(); // GIVEN @@ -236,8 +229,8 @@ public void test120ModifyBob() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - RepoOpAsserter repoOpAsserter = createRepoOpAsserter(TEST_NAME).display(); - dumpThreadLocalCachePerformanceData(TEST_NAME); + RepoOpAsserter repoOpAsserter = createRepoOpAsserter().display(); + dumpThreadLocalCachePerformanceData(); assertUser(USER_BOB_OID, "bob") .assertFullName("Bob Brown") diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationPerf.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationPerf.java index 47276fc6d25..d9787cf755d 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationPerf.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOperationPerf.java @@ -88,8 +88,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - assertObjects(RoleType.class, NUMBER_OF_GENERATED_EMPTY_ROLES + NUMBER_OF_ORDINARY_ROLES); display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); @@ -98,17 +96,15 @@ public void test000Sanity() throws Exception { @Test public void test100AddAlice() throws Exception { - final String TEST_NAME = "test100AddAlice"; - testAddUser(TEST_NAME, USER_ALICE_FILE, USER_ALICE_OID, 1); + testAddUser(USER_ALICE_FILE, USER_ALICE_OID, 1); } @Test public void test110AddBob() throws Exception { - final String TEST_NAME = "test110AddBob"; - testAddUser(TEST_NAME, USER_BOB_FILE, USER_BOB_OID, 1); + testAddUser(USER_BOB_FILE, USER_BOB_OID, 1); } - public void testAddUser(final String TEST_NAME, File userFile, String userOid, int roles) throws Exception { + public void testAddUser(File userFile, String userOid, int roles) throws Exception { Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOrgSync.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOrgSync.java index 4c6145ede8f..abb64503e46 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOrgSync.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestOrgSync.java @@ -6,16 +6,11 @@ * and European Union Public License. See LICENSE file for details. */ -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.Collection; import java.util.List; - import javax.xml.namespace.QName; import org.opends.server.types.DirectoryException; @@ -40,26 +35,14 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentPolicyEnforcementType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationResultType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.TaskType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.util.exception.*; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; /** * @author Radovan Semancik - * */ @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -79,13 +62,12 @@ public class TestOrgSync extends AbstractStoryTest { protected static final File RESOURCE_DUMMY_HR_FILE = new File(TEST_DIR, "resource-dummy-hr.xml"); protected static final String RESOURCE_DUMMY_HR_ID = "HR"; protected static final String RESOURCE_DUMMY_HR_OID = "10000000-0000-0000-0000-000000000001"; - protected static final String RESOURCE_DUMMY_HR_NAMESPACE = MidPointConstants.NS_RI; protected static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; protected static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - protected static final QName OPENDJ_ASSOCIATION_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, - "group"); + protected static final QName OPENDJ_ASSOCIATION_GROUP_NAME = + new QName(RESOURCE_OPENDJ_NAMESPACE, "group"); private static final String DUMMY_ACCOUNT_ATTRIBUTE_HR_ORGPATH = "orgpath"; private static final String DUMMY_ACCOUNT_ATTRIBUTE_HR_RESPONSIBILITIES = "responsibilities"; @@ -102,8 +84,6 @@ public class TestOrgSync extends AbstractStoryTest { public static final File ROLE_META_RESPONSIBILITY_FILE = new File(TEST_DIR, "role-meta-responsibility.xml"); - public static final String ROLE_META_RESPONSIBILITY_OID = "10000000-0000-0000-0000-000000006602"; - protected static final File TASK_LIVE_SYNC_DUMMY_HR_FILE = new File(TEST_DIR, "task-dumy-hr-livesync.xml"); protected static final String TASK_LIVE_SYNC_DUMMY_HR_OID = "10000000-0000-0000-5555-555500000001"; @@ -198,7 +178,7 @@ public class TestOrgSync extends AbstractStoryTest { protected static final int TASK_WAIT_TIMEOUT = 40000; - @Autowired(required = true) + @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; private DebugReconciliationTaskResultListener reconciliationTaskResultListener; @@ -225,7 +205,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -238,17 +218,17 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti // Resources initDummyResource(RESOURCE_DUMMY_HR_ID, RESOURCE_DUMMY_HR_FILE, RESOURCE_DUMMY_HR_OID, c -> { - DummyObjectClass dummyAdAccountObjectClass = c.getDummyResource().getAccountObjectClass(); - c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, - String.class, false, false); - c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, - String.class, false, false); - c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_ORGPATH, - String.class, false, false); - c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_RESPONSIBILITIES, - String.class, false, true); - c.getDummyResource().setSyncStyle(DummySyncStyle.SMART); - } , initTask, initResult); + DummyObjectClass dummyAdAccountObjectClass = c.getDummyResource().getAccountObjectClass(); + c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, + String.class, false, false); + c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, + String.class, false, false); + c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_ORGPATH, + String.class, false, false); + c.addAttrDef(dummyAdAccountObjectClass, DUMMY_ACCOUNT_ATTRIBUTE_HR_RESPONSIBILITIES, + String.class, false, true); + c.getDummyResource().setSyncStyle(DummySyncStyle.SMART); + }, initTask, initResult); dummyResourceHr = getDummyResource(RESOURCE_DUMMY_HR_ID); resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, @@ -286,7 +266,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; Task task = getTestTask(); OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_HR_OID, task); @@ -307,9 +286,6 @@ public void test000Sanity() throws Exception { */ @Test public void test100AddHrAccountHerman() throws Exception { - final String TEST_NAME = "test100AddHrAccountHerman"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_HERMAN_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_HERMAN_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_HERMAN_LAST_NAME); @@ -346,9 +322,6 @@ public void test100AddHrAccountHerman() throws Exception { */ @Test public void test105AddHrAccountLemonhead() throws Exception { - final String TEST_NAME = "test105AddHrAccountLemonhead"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_LEMONHEAD_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_LEMONHEAD_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_LEMONHEAD_LAST_NAME); @@ -390,9 +363,6 @@ public void test105AddHrAccountLemonhead() throws Exception { */ @Test public void test106AddHrAccountSharptooth() throws Exception { - final String TEST_NAME = "test106AddHrAccountSharptooth"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_SHARPTOOTH_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_SHARPTOOTH_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_SHARPTOOTH_LAST_NAME); @@ -433,9 +403,6 @@ public void test106AddHrAccountSharptooth() throws Exception { */ @Test public void test107AddHrAccountRedskull() throws Exception { - final String TEST_NAME = "test107AddHrAccountRedskull"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_REDSKULL_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_REDSKULL_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_REDSKULL_LAST_NAME); @@ -475,9 +442,6 @@ public void test107AddHrAccountRedskull() throws Exception { */ @Test public void test108RedskullGoesVegetarian() throws Exception { - final String TEST_NAME = "test108RedskullGoesVegetarian"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount account = dummyResourceHr.getAccountByUsername(ACCOUNT_REDSKULL_USERNAME); // WHEN @@ -515,9 +479,6 @@ public void test108RedskullGoesVegetarian() throws Exception { */ @Test public void test109HrDeleteRedskull() throws Exception { - final String TEST_NAME = "test109HrDeleteRedskull"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - // WHEN when(); dummyResourceHr.deleteAccountByName(ACCOUNT_REDSKULL_USERNAME); @@ -544,9 +505,6 @@ public void test109HrDeleteRedskull() throws Exception { */ @Test public void test110AddHrAccountGuybrush() throws Exception { - final String TEST_NAME = "test110AddHrAccountGuybrush"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_GUYBRUSH_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_GUYBRUSH_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_GUYBRUSH_LAST_NAME); @@ -589,9 +547,6 @@ public void test110AddHrAccountGuybrush() throws Exception { */ @Test public void test115AddHrAccountMancomb() throws Exception { - final String TEST_NAME = "test115AddHrAccountMancomb"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_MANCOMB_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_MANCOMB_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_MANCOMB_LAST_NAME); @@ -635,9 +590,6 @@ public void test115AddHrAccountMancomb() throws Exception { */ @Test public void test117AddHrAccountCobb() throws Exception { - final String TEST_NAME = "test117AddHrAccountCobb"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_COBB_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_COBB_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_COBB_LAST_NAME); @@ -681,9 +633,6 @@ public void test117AddHrAccountCobb() throws Exception { */ @Test public void test130AddHrAccountLargo() throws Exception { - final String TEST_NAME = "test130AddHrAccountLargo"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_LARGO_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_LARGO_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_LARGO_LAST_NAME); @@ -733,9 +682,6 @@ public void test130AddHrAccountLargo() throws Exception { */ @Test public void test140AddHrAccountWally() throws Exception { - final String TEST_NAME = "test140AddHrAccountWally"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_WALLY_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_WALLY_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_WALLY_LAST_NAME); @@ -776,9 +722,6 @@ public void test140AddHrAccountWally() throws Exception { */ @Test public void test142AddHrAccountAugustus() throws Exception { - final String TEST_NAME = "test142AddHrAccountAugustus"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_AUGUSTUS_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_AUGUSTUS_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_AUGUSTUS_LAST_NAME); @@ -819,9 +762,6 @@ public void test142AddHrAccountAugustus() throws Exception { */ @Test public void test185AddHrAccountStan() throws Exception { - final String TEST_NAME = "test185AddHrAccountStan"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_STAN_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_STAN_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_STAN_LAST_NAME); @@ -864,9 +804,6 @@ public void test185AddHrAccountStan() throws Exception { */ @Test public void test186AddHrAccountCapsize() throws Exception { - final String TEST_NAME = "test186AddHrAccountCapsize"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_CAPSIZE_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_CAPSIZE_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_CAPSIZE_LAST_NAME); @@ -909,9 +846,6 @@ public void test186AddHrAccountCapsize() throws Exception { */ @Test public void test187AddHrAccountRogersSr() throws Exception { - final String TEST_NAME = "test187AddHrAccountRogersSr"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_ROGERSSR_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_ROGERSSR_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_ROGERSSR_LAST_NAME); @@ -955,9 +889,6 @@ public void test187AddHrAccountRogersSr() throws Exception { */ @Test public void test190AddHrAccountTeleke() throws Exception { - final String TEST_NAME = "test190AddHrAccountTeleke"; - Task task = taskManager.createTaskInstance(TestOrgSync.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_TELEKE_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_FIRST_NAME, ACCOUNT_TELEKE_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_HR_LAST_NAME, ACCOUNT_TELEKE_LAST_NAME); @@ -997,8 +928,6 @@ public void test190AddHrAccountTeleke() throws Exception { @Test public void test500ReconcileOpenDJDefault() throws Exception { - final String TEST_NAME = "test500ReconcileOpenDJDefault"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1041,11 +970,8 @@ public void test500ReconcileOpenDJDefault() throws Exception { @Test public void test502ReconcileOpenDJDefaultAgain() throws Exception { - final String TEST_NAME = "test502ReconcileOpenDJDefaultAgain"; // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); assertUsers(18); @@ -1077,8 +1003,6 @@ public void test502ReconcileOpenDJDefaultAgain() throws Exception { @Test public void test510ReconcileOpenDJLdapGroup() throws Exception { - final String TEST_NAME = "test510ReconcileOpenDJLdapGroup"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1120,14 +1044,10 @@ public void test510ReconcileOpenDJLdapGroup() throws Exception { @Test public void test550ReconcileOpenDJAfterMembershipChange() throws Exception { - final String TEST_NAME = "test550ReconcileOpenDJAfterMembershipChange"; - // We manually remove Lemonhead from R_canibalism group // And check whether reconciliation re-adds him again // GIVEN - Task task = getTestTask(); - OperationResult result = task.getResult(); assumeAssignmentPolicy(AssignmentPolicyEnforcementType.RELATIVE); Collection membersBeforeTest = openDJController.getGroupUniqueMembers(RESP_CANIBALISM_DN); @@ -1194,9 +1114,9 @@ private PrismObject getAndAssertReplicatedOrg(String orgName) // TODO assert shadow content Entry ouEntry = openDJController.searchSingle("ou=" + orgName); - assertNotNull("No ou LDAP entry for " + orgName); + assertNotNull("No ou LDAP entry for " + orgName, ouEntry); display("OU entry", ouEntry); - openDJController.assertObjectClass(ouEntry, "organizationalUnit"); + OpenDJController.assertObjectClass(ouEntry, "organizationalUnit"); return org; } @@ -1215,7 +1135,7 @@ private String assertResponsibility(PrismObject user, String respName) CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { String respRoleName = "R_" + respName; PrismObject respRole = searchObjectByName(RoleType.class, respRoleName); - assertNotNull("No role for responsibility " + respName); + assertNotNull("No role for responsibility " + respName, respRole); display("Responsibility role for " + respName, respRole); assertAssignedRole(user, respRole.getOid()); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java index 0d5f862cc95..6f7a0b3574e 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestPlentyOfAssignments.java @@ -146,8 +146,6 @@ private String formatGroupName(int num) { @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - assertObjects(RoleType.class, NUMBER_OF_GENERATED_EMPTY_ROLES + NUMBER_OF_GENERATED_DUMMY_ROLES + NUMBER_OF_ORDINARY_ROLES); display("Repo reads", InternalMonitor.getCount(InternalCounters.REPOSITORY_READ_COUNT)); @@ -156,8 +154,6 @@ public void test000Sanity() throws Exception { @Test public void test100AddCheese() throws Exception { - final String TEST_NAME = "test100AddCheese"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -198,8 +194,6 @@ public void test100AddCheese() throws Exception { @Test public void test110RecomputeCheese() throws Exception { - final String TEST_NAME = "test110RecomputeCheese"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -239,8 +233,6 @@ public void test110RecomputeCheese() throws Exception { @Test public void test120CheesePreviewChanges() throws Exception { - final String TEST_NAME = "test120CheesePreviewChanges"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -306,8 +298,6 @@ private void assertCheeseRoleMembershipRef(PrismObject cheese) { */ @Test public void test200DummyGroups() throws Exception { - final String TEST_NAME = "test200DummyGroups"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -380,8 +370,6 @@ public void test200DummyGroups() throws Exception { */ @Test public void test210AddBob() throws Exception { - final String TEST_NAME = "test210AddBob"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -428,8 +416,6 @@ public void test210AddBob() throws Exception { */ @Test public void test212RecomputeBob() throws Exception { - final String TEST_NAME = "test212RecomputeBob"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -472,8 +458,6 @@ public void test212RecomputeBob() throws Exception { */ @Test public void test2124ReconcileBob() throws Exception { - final String TEST_NAME = "test212RecomputeBob"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -534,8 +518,6 @@ private void assertBobDummy(int expectedBottlesOfRum) throws Exception { */ @Test public void test220AddAlice() throws Exception { - final String TEST_NAME = "test220AddAlice"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -584,8 +566,6 @@ public void test220AddAlice() throws Exception { */ @Test public void test222RecomputeAlice() throws Exception { - final String TEST_NAME = "test222RecomputeAlice"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -628,8 +608,6 @@ public void test222RecomputeAlice() throws Exception { */ @Test public void test224ReconcileAlice() throws Exception { - final String TEST_NAME = "test224ReconcileAlice"; - Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestReconNullValue.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestReconNullValue.java index f8b782b990d..acec70abe03 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestReconNullValue.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestReconNullValue.java @@ -11,11 +11,7 @@ import static org.testng.AssertJUnit.assertNotNull; import java.io.File; -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collection; -import java.util.Collections; -import java.util.List; +import java.util.*; import org.opends.server.types.DirectoryException; import org.springframework.test.annotation.DirtiesContext; @@ -28,50 +24,36 @@ import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.processor.ResourceAttribute; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +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; /** - * * Recon should delete resourceAttributes - * + *

* resourceAttributes title and givenName have strong mappings * title has source honorificPrefix * givenName has source givenName - * + *

* focus attributes honorificPrefix and/or givenName do not exist and resourceAttributes title and givenName are added manually * -> reconcile should remove resourceAtributes * as of git-v3.7.1-57-gc5757c3b0d this seems to work for honorificPrefix/title but not for givenName/givenName * * @author michael gruber - * */ @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestReconNullValue extends AbstractStoryTest { - public static final File TEST_DIR = new File(MidPointTestConstants.TEST_RESOURCES_DIR, "recon-null-value"); private static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; - private static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; public static final String ORG_TOP_OID = "00000000-8888-6666-0000-100000000001"; public static final String OBJECT_TEMPLATE_USER_OID = "10000000-0000-0000-0000-000000000222"; @@ -83,10 +65,6 @@ public class TestReconNullValue extends AbstractStoryTest { private static final String ACCOUNT_ATTRIBUTE_TITLE = "title"; private static final String ACCOUNT_ATTRIBUTE_GIVENNAME = "givenName"; - - private ResourceType resourceOpenDjType; - private PrismObject resourceOpenDj; - @Override protected String getTopOrgOid() { return ORG_TOP_OID; @@ -96,14 +74,13 @@ private File getTestDir() { return TEST_DIR; } - @Override protected void startResources() throws Exception { openDJController.startCleanServerRI(); } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -112,8 +89,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti super.initSystem(initTask, initResult); //Resources - resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, new File(getTestDir(), "resource-opendj.xml"), RESOURCE_OPENDJ_OID, initTask, initResult); - resourceOpenDjType = resourceOpenDj.asObjectable(); + PrismObject resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, new File(getTestDir(), "resource-opendj.xml"), RESOURCE_OPENDJ_OID, initTask, initResult); openDJController.setResource(resourceOpenDj); //org @@ -129,8 +105,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestReconNullValue.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); @@ -140,17 +115,13 @@ public void test000Sanity() throws Exception { display("FINISHED: test000Sanity"); } - - @Test public void test100CreateUsers() throws Exception { - final String TEST_NAME = "test200CreateUsers"; - Task task = taskManager.createTaskInstance(TestReconNullValue.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject user0Before = createUser(USER_0_NAME, "givenName0", "familyName0", true); - // WHEN when(); display("Adding user0", user0Before); @@ -166,27 +137,22 @@ public void test100CreateUsers() throws Exception { dumpOrgTree(); - assertShadowAttribute(user0After, ShadowKindType.ACCOUNT, LDAP_INTENT_DEFAULT, ACCOUNT_ATTRIBUTE_GIVENNAME, "givenName0"); - + assertShadowAttribute(user0After, ShadowKindType.ACCOUNT, LDAP_INTENT_DEFAULT, ACCOUNT_ATTRIBUTE_GIVENNAME, "givenName0"); } /** * add honorificPrefix - * + *

* in resource account value for title should have been added - * */ @Test public void test130AddHonorificPrefix() throws Exception { - final String TEST_NAME = "test140AddHonorificPrefix"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); - //TODO: best way to set extension properties? PrismObject userBefore = getObjectByName(UserType.class, USER_0_NAME); display("User before", userBefore); @@ -204,7 +170,6 @@ public void test130AddHonorificPrefix() throws Exception { when(); modelService.executeChanges(deltas, null, task, result); - // THEN then(); assertSuccess(result); @@ -222,27 +187,23 @@ public void test130AddHonorificPrefix() throws Exception { PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("accountModel after attribute deletion", accountModel); - assertShadowAttribute(userAfter, ShadowKindType.ACCOUNT, LDAP_INTENT_DEFAULT, ACCOUNT_ATTRIBUTE_GIVENNAME, "givenName0"); - assertShadowAttribute(userAfter, ShadowKindType.ACCOUNT, LDAP_INTENT_DEFAULT, ACCOUNT_ATTRIBUTE_TITLE, "Princess"); + assertShadowAttribute(userAfter, ShadowKindType.ACCOUNT, LDAP_INTENT_DEFAULT, ACCOUNT_ATTRIBUTE_GIVENNAME, "givenName0"); + assertShadowAttribute(userAfter, ShadowKindType.ACCOUNT, LDAP_INTENT_DEFAULT, ACCOUNT_ATTRIBUTE_TITLE, "Princess"); } /** * delete honorificPrefix and givenName - * + *

* in resource account value for title and givenName should have been deleted - * */ @Test public void test140dDeleteHonorificPrefixGivenName() throws Exception { - final String TEST_NAME = "test140dDeleteHonorificPrefixGivenName"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); - //TODO: best way to set extension properties? PrismObject userBefore = getObjectByName(UserType.class, USER_0_NAME); display("User before", userBefore); @@ -261,7 +222,6 @@ public void test140dDeleteHonorificPrefixGivenName() throws Exception { when(); modelService.executeChanges(deltas, null, task, result); - // THEN then(); assertSuccess(result); @@ -269,7 +229,6 @@ public void test140dDeleteHonorificPrefixGivenName() throws Exception { PrismObject userAfter = getObjectByName(UserType.class, USER_0_NAME); display("User after deleting attribute honorificPrefix", userAfter); - String accountOid = getLinkRefOid(userAfter, RESOURCE_OPENDJ_OID); // Check shadow @@ -285,31 +244,25 @@ public void test140dDeleteHonorificPrefixGivenName() throws Exception { } - /** * add title in resource account (not using midpoint) * do recompute * in resource account value for title should have been removed again - * */ @Test public void test150RemoveTitleRA() throws Exception { - final String TEST_NAME = "test150RemoveTitleRA"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); - //TODO: best way to set extension properties? PrismObject userBefore = getObjectByName(UserType.class, USER_0_NAME); display("User before", userBefore); - - openDJController.executeLdifChange("dn: uid="+USER_0_NAME+",ou=people,dc=example,dc=com\n"+ - "changetype: modify\n"+ - "add: title\n"+ + openDJController.executeLdifChange("dn: uid=" + USER_0_NAME + ",ou=people,dc=example,dc=com\n" + + "changetype: modify\n" + + "add: title\n" + "title: Earl"); display("LDAP after addition"); @@ -329,7 +282,6 @@ public void test150RemoveTitleRA() throws Exception { PrismObject userAfter = getObjectByName(UserType.class, USER_0_NAME); display("User smack after adding attribute title", userAfter); - String accountOid = getLinkRefOid(userAfter, RESOURCE_OPENDJ_OID); // Check shadow @@ -340,7 +292,7 @@ public void test150RemoveTitleRA() throws Exception { PrismObject accountModel = modelService.getObject(ShadowType.class, accountOid, null, task, result); display("accountModel after attribute addition", accountModel); - PrismAsserts.assertNoItem(accountModel, openDJController.getAttributePath( ACCOUNT_ATTRIBUTE_TITLE)); + PrismAsserts.assertNoItem(accountModel, openDJController.getAttributePath(ACCOUNT_ATTRIBUTE_TITLE)); } @@ -349,26 +301,21 @@ public void test150RemoveTitleRA() throws Exception { * do recompute * in resource account value for givenName should have been removed again * See also https://wiki.evolveum.com/display/midPoint/Resource+Schema+Handling#ResourceSchemaHandling-AttributeTolerance - * */ @Test //MID-4567 public void test160SetGivenNameAttributeAndReconcile() throws Exception { - final String TEST_NAME = "test160SetGivenNameAttributeAndReconcile"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); dummyAuditService.clear(); - //TODO: best way to set extension properties? PrismObject userBefore = getObjectByName(UserType.class, USER_0_NAME); display("User before", userBefore); - - openDJController.executeLdifChange("dn: uid="+USER_0_NAME+",ou=people,dc=example,dc=com\n"+ - "changetype: modify\n"+ - "replace: givenName\n"+ + openDJController.executeLdifChange("dn: uid=" + USER_0_NAME + ",ou=people,dc=example,dc=com\n" + + "changetype: modify\n" + + "replace: givenName\n" + "givenName: given0again"); display("LDAP after addition"); @@ -388,7 +335,6 @@ public void test160SetGivenNameAttributeAndReconcile() throws Exception { PrismObject userAfter = getObjectByName(UserType.class, USER_0_NAME); display("User smack after adding attribute title", userAfter); - String accountOid = getLinkRefOid(userAfter, RESOURCE_OPENDJ_OID); // Check shadow @@ -408,8 +354,6 @@ public void test160SetGivenNameAttributeAndReconcile() throws Exception { */ @Test //MID-4567 public void test170ReplaceGivenNameEmpty() throws Exception { - final String TEST_NAME = "test170ReplaceGivenNameEmpty"; - // GIVEN Task task = getTestTask(); OperationResult result = task.getResult(); @@ -418,9 +362,9 @@ public void test170ReplaceGivenNameEmpty() throws Exception { PrismObject userBefore = getObjectByName(UserType.class, USER_0_NAME); display("User before", userBefore); - openDJController.executeLdifChange("dn: uid="+USER_0_NAME+",ou=people,dc=example,dc=com\n"+ - "changetype: modify\n"+ - "replace: givenName\n"+ + openDJController.executeLdifChange("dn: uid=" + USER_0_NAME + ",ou=people,dc=example,dc=com\n" + + "changetype: modify\n" + + "replace: givenName\n" + "givenName: given1again"); display("LDAP after addition"); @@ -440,7 +384,6 @@ public void test170ReplaceGivenNameEmpty() throws Exception { PrismObject userAfter = getObjectByName(UserType.class, USER_0_NAME); display("User smack after adding attribute title", userAfter); - String accountOid = getLinkRefOid(userAfter, RESOURCE_OPENDJ_OID); // Check shadow @@ -460,9 +403,8 @@ private void dumpLdap() throws DirectoryException { display("LDAP server content", openDJController.dumpEntries()); } - - protected PrismObject getObjectByName( - Class clazz, String name) throws SchemaException, ObjectNotFoundException, SecurityViolationException, + protected PrismObject getObjectByName(Class clazz, String name) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { PrismObject object = (PrismObject) findObjectByName(clazz, name); assertNotNull("The object " + name + " of type " + clazz + " is missing!", object); @@ -471,9 +413,10 @@ protected objShadow = getShadowModel(objOid); display("Focus " + focusName + " kind " + kind + " intent " + intent + " shadow", objShadow); - List valuesList = new ArrayList(Arrays.asList(values)); + List valuesList = new ArrayList<>(Arrays.asList(values)); for (Object att : objShadow.asObjectable().getAttributes().asPrismContainerValue().getItems()) { if (att instanceof ResourceAttribute) { @@ -489,7 +432,7 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin if (attribute.equals(((ResourceAttribute) att).getNativeAttributeName())) { - List propValsString = new ArrayList(propVals.size()); + List propValsString = new ArrayList<>(propVals.size()); for (Object pval : propVals) { propValsString.add(pval.toString()); } @@ -503,5 +446,4 @@ private void assertShadowAttribute(PrismObject focus, ShadowKindType kind, Strin } } } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestRetirement.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestRetirement.java index 16995a607a3..57c8bacaac8 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestRetirement.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestRetirement.java @@ -7,18 +7,12 @@ package com.evolveum.midpoint.testing.story; - -import static com.evolveum.midpoint.test.IntegrationTestTools.assertAttribute; -import static com.evolveum.midpoint.test.IntegrationTestTools.display; -import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; import java.io.File; import java.util.ArrayList; import java.util.Collection; -import javax.xml.namespace.QName; - import org.opends.server.types.DirectoryException; import org.opends.server.types.Entry; import org.springframework.test.annotation.DirtiesContext; @@ -32,40 +26,22 @@ import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.util.PrismAsserts; import com.evolveum.midpoint.prism.util.PrismTestUtil; -import com.evolveum.midpoint.schema.ResultHandler; import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.constants.SchemaConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.MiscSchemaUtil; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommonException; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectAlreadyExistsException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.PolicyViolationException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; -import com.evolveum.midpoint.util.exception.SystemException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +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; /** * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestRetirement extends AbstractStoryTest { @@ -74,23 +50,19 @@ public class TestRetirement extends AbstractStoryTest { protected static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; protected static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - protected static final QName OPENDJ_ASSOCIATION_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "group"); public static final File ORG_TOP_FILE = new File(TEST_DIR, "org-top.xml"); public static final String ORG_TOP_OID = "00000000-8888-6666-0000-100000000001"; public static final File ORG_RETIRED_FILE = new File(TEST_DIR, "org-retired.xml"); public static final String ORG_RETIRED_OID = "00000000-8888-6666-0000-100000ffffff"; - public static final String ORG_RETIRED_NAME = "RETIRED"; public static final File ROLE_META_ORG_FILE = new File(TEST_DIR, "role-meta-org.xml"); public static final String ROLE_META_ORG_OID = "10000000-0000-0000-0000-000000006601"; protected static final String ORG_ROYULA_CARPATHIA_NAME = "Royula Carpathia"; protected static final String ORG_CORTUV_HRAD_NAME = "Čortův hrád"; - protected static final String ORG_CORTUV_HRAD_NAME2 = "ani zblo"; protected static final String ORG_VYSNE_VLKODLAKY_NAME = "Vyšné Vlkodlaky"; - protected static final String ORG_ROYULA_DIABOLICA_NAME = "Royula Diábolica"; protected static final String ORG_TYPE_FUNCTIONAL = "functional"; @@ -102,7 +74,6 @@ public class TestRetirement extends AbstractStoryTest { protected static final String USER_TELEKE_FAMILY_NAME = "Teleke z Tölökö"; protected static final String USER_GORC_USERNAME = "gorc"; - protected static final String USER_GORC_USERNAME2 = "obluda"; protected static final String USER_GORC_GIVEN_NAME = "Robert"; protected static final String USER_GORC_FAMILY_NAME = "Gorc z Gorců"; @@ -116,7 +87,6 @@ public class TestRetirement extends AbstractStoryTest { protected String orgRolyulaCarpathiaOid; protected String orgCortuvHradOid; protected String orgVysneVlkodlakyOid; - protected String orgRolyulaDiabolicaOid; protected String userGorcOid; @Override @@ -130,7 +100,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -138,7 +108,6 @@ public static void stopResources() throws Exception { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - // Resources resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, RESOURCE_OPENDJ_FILE, RESOURCE_OPENDJ_OID, initTask, initResult); resourceOpenDjType = resourceOpenDj.asObjectable(); @@ -153,8 +122,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); @@ -165,8 +133,7 @@ public void test000Sanity() throws Exception { @Test public void test050AddOrgRetired() throws Exception { - final String TEST_NAME = "test050AddOrgRetired"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject orgBefore = PrismTestUtil.parseObject(ORG_RETIRED_FILE); @@ -194,17 +161,16 @@ public void test050AddOrgRetired() throws Exception { // TODO assert shadow content Entry ouEntry = openDJController.fetchEntry(ouShadow.getName().getOrig()); - assertNotNull("No ou LDAP entry for retirement ("+ouShadow.getName().getOrig()+")", ouEntry); + assertNotNull("No ou LDAP entry for retirement (" + ouShadow.getName().getOrig() + ")", ouEntry); display("OU retirement entry", openDJController.toHumanReadableLdifoid(ouEntry)); - openDJController.assertObjectClass(ouEntry, "organizationalUnit"); + OpenDJController.assertObjectClass(ouEntry, "organizationalUnit"); assertSubOrgs(org, 0); } @Test public void test100AddOrgRoyulaCarpathia() throws Exception { - final String TEST_NAME = "test100AddOrgRoyulaCarpathia"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); @@ -231,8 +197,7 @@ public void test100AddOrgRoyulaCarpathia() throws Exception { @Test public void test110AddUserTeleke() throws Exception { - final String TEST_NAME = "test110AddUserTeleke"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = createUser(USER_TELEKE_USERNAME, @@ -248,7 +213,7 @@ public void test110AddUserTeleke() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = getAndAssertUser(USER_TELEKE_USERNAME, ORG_ROYULA_CARPATHIA_NAME); + getAndAssertUser(USER_TELEKE_USERNAME); PrismObject orgAfter = getAndAssertFunctionalOrg(ORG_ROYULA_CARPATHIA_NAME, ORG_TOP_OID); @@ -261,8 +226,7 @@ public void test110AddUserTeleke() throws Exception { @Test public void test200AddOrgCortuvHrad() throws Exception { - final String TEST_NAME = "test200AddOrgCortuvHrad"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_CORTUV_HRAD_NAME, orgRolyulaCarpathiaOid); @@ -290,8 +254,7 @@ public void test200AddOrgCortuvHrad() throws Exception { @Test public void test210AddUserGorc() throws Exception { - final String TEST_NAME = "test210AddUserGorc"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = createUser(USER_GORC_USERNAME, @@ -307,7 +270,7 @@ public void test210AddUserGorc() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = getAndAssertUser(USER_GORC_USERNAME, ORG_CORTUV_HRAD_NAME, ORG_ROYULA_CARPATHIA_NAME); + PrismObject userAfter = getAndAssertUser(USER_GORC_USERNAME); userGorcOid = userAfter.getOid(); dumpOrgTree(); @@ -316,8 +279,7 @@ public void test210AddUserGorc() throws Exception { @Test public void test220AddOrgVysneVlkodlaky() throws Exception { - final String TEST_NAME = "test220AddOrgVysneVlkodlaky"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject orgBefore = createOrg(ORG_VYSNE_VLKODLAKY_NAME, orgCortuvHradOid); @@ -345,8 +307,7 @@ public void test220AddOrgVysneVlkodlaky() throws Exception { @Test public void test230AddUserViljaDezi() throws Exception { - final String TEST_NAME = "test230AddUserViljaDezi"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = createUser(USER_DEZI_USERNAME, @@ -362,7 +323,7 @@ public void test230AddUserViljaDezi() throws Exception { result.computeStatus(); TestUtil.assertSuccess(result); - PrismObject userAfter = getAndAssertUser(USER_DEZI_USERNAME, ORG_VYSNE_VLKODLAKY_NAME, ORG_CORTUV_HRAD_NAME, ORG_ROYULA_CARPATHIA_NAME); + getAndAssertUser(USER_DEZI_USERNAME); dumpOrgTree(); dumpLdap(); @@ -370,11 +331,10 @@ public void test230AddUserViljaDezi() throws Exception { @Test public void test300RetireUserGorc() throws Exception { - final String TEST_NAME = "test300RetireUserGorc"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); - Collection> modifications = new ArrayList<>(); + Collection> modifications = new ArrayList<>(); modifications.add(createAssignmentModification(orgCortuvHradOid, OrgType.COMPLEX_TYPE, null, null, null, false)); modifications.add(createAssignmentModification(ORG_RETIRED_OID, OrgType.COMPLEX_TYPE, null, null, null, true)); ObjectDelta userDelta = prismContext.deltaFactory().object() @@ -399,8 +359,7 @@ public void test300RetireUserGorc() throws Exception { @Test public void test302ReconcileUserGorc() throws Exception { - final String TEST_NAME = "test302ReconcileUserGorc"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -421,8 +380,7 @@ public void test302ReconcileUserGorc() throws Exception { @Test public void test303ReconcileUserGorcAgain() throws Exception { - final String TEST_NAME = "test303ReconcileUserGorcAgain"; - Task task = taskManager.createTaskInstance(TestRetirement.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); // WHEN @@ -482,37 +440,38 @@ private PrismObject createOrg(String name, String parentOrgOid) throws return org; } - private PrismObject getAndAssertUser(String username, String directOrgGroupname, String... indirectGroupNames) throws SchemaException, CommonException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { + private PrismObject getAndAssertUser(String username) + throws CommonException, DirectoryException { PrismObject user = findUserByUsername(username); display("user", user); String shadowOid = getLinkRefOid(user, RESOURCE_OPENDJ_OID, ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT); PrismObject accountShadow = getShadowModel(shadowOid); - display("Account "+username+" shadow", accountShadow); + display("Account " + username + " shadow", accountShadow); // TODO assert shadow content - Entry accountEntry = openDJController.searchSingle("uid="+username); - assertNotNull("No account LDAP entry for "+username, accountEntry); + Entry accountEntry = openDJController.searchSingle("uid=" + username); + assertNotNull("No account LDAP entry for " + username, accountEntry); display("account entry", openDJController.toHumanReadableLdifoid(accountEntry)); - openDJController.assertObjectClass(accountEntry, "inetOrgPerson"); + OpenDJController.assertObjectClass(accountEntry, "inetOrgPerson"); return user; } - private PrismObject getAndAssertRetiredUser(String username) throws SchemaException, CommonException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { + private PrismObject getAndAssertRetiredUser(String username) throws CommonException, DirectoryException { PrismObject user = findUserByUsername(username); display("user", user); String shadowOid = getLinkRefOid(user, RESOURCE_OPENDJ_OID, ShadowKindType.ACCOUNT, SchemaConstants.INTENT_DEFAULT); PrismObject accountShadow = getShadowModel(shadowOid); - display("Account "+username+" shadow", accountShadow); + display("Account " + username + " shadow", accountShadow); // TODO assert shadow content - String dn = "uid=RRR-"+username+",ou=RETIRED,dc=example,dc=com"; + String dn = "uid=RRR-" + username + ",ou=RETIRED,dc=example,dc=com"; Entry accountEntry = openDJController.fetchEntry(dn); - assertNotNull("No account LDAP entry for "+username+" ("+dn+")", accountEntry); + assertNotNull("No account LDAP entry for " + username + " (" + dn + ")", accountEntry); display("account entry", openDJController.toHumanReadableLdifoid(accountEntry)); - openDJController.assertObjectClass(accountEntry, "inetOrgPerson"); + OpenDJController.assertObjectClass(accountEntry, "inetOrgPerson"); return user; } @@ -525,13 +484,13 @@ private PrismObject getAndAssertFunctionalOrg(String orgName, String di String groupOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, LDAP_GROUP_INTENT); PrismObject groupShadow = getShadowModel(groupOid); - display("Org "+orgName+" group shadow", groupShadow); + display("Org " + orgName + " group shadow", groupShadow); // TODO assert shadow content - Entry groupEntry = openDJController.searchSingle("cn="+orgName); - assertNotNull("No group LDAP entry for "+orgName, groupEntry); + Entry groupEntry = openDJController.searchSingle("cn=" + orgName); + assertNotNull("No group LDAP entry for " + orgName, groupEntry); display("OU GROUP entry", openDJController.toHumanReadableLdifoid(groupEntry)); - openDJController.assertObjectClass(groupEntry, "groupOfUniqueNames"); + OpenDJController.assertObjectClass(groupEntry, "groupOfUniqueNames"); assertHasOrg(org, directParentOrgOid); assertAssignedOrg(org, directParentOrgOid); @@ -543,59 +502,4 @@ private void dumpLdap() throws DirectoryException { display("LDAP server tree", openDJController.dumpTree()); display("LDAP server content", openDJController.dumpEntries()); } - - private void assertGroupMembers(PrismObject org, String... members) throws Exception { - String groupOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "org-group"); - PrismObject groupShadow = getShadowModel(groupOid); - assertAttribute(groupShadow.asObjectable(), new QName(MidPointConstants.NS_RI, "uniqueMember"), members); - } - - private void assertNoGroupMembers(PrismObject org) throws Exception { - String groupOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "org-group"); - PrismObject groupShadow = getShadowModel(groupOid); - assertNoAttribute(groupShadow.asObjectable(), new QName(MidPointConstants.NS_RI, "uniqueMember")); - } - - private void reconcileAllUsers() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - final Task task = getTestTask(); - OperationResult result = task.getResult(); - ResultHandler handler = new ResultHandler() { - @Override - public boolean handle(PrismObject object, OperationResult parentResult) { - try { - display("reconciling "+object); - reconcileUser(object.getOid(), task, parentResult); - } catch (SchemaException | PolicyViolationException | ExpressionEvaluationException - | ObjectNotFoundException | ObjectAlreadyExistsException | CommunicationException - | ConfigurationException | SecurityViolationException e) { - throw new SystemException(e.getMessage(), e); - } - return true; - } - }; - display("Reconciling all users"); - modelService.searchObjectsIterative(UserType.class, null, handler, null, task, result); - } - - private void reconcileAllOrgs() throws SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, SecurityViolationException, ExpressionEvaluationException { - final Task task = getTestTask(); - OperationResult result = task.getResult(); - ResultHandler handler = new ResultHandler() { - @Override - public boolean handle(PrismObject object, OperationResult parentResult) { - try { - display("reconciling "+object); - reconcileOrg(object.getOid(), task, parentResult); - } catch (SchemaException | PolicyViolationException | ExpressionEvaluationException - | ObjectNotFoundException | ObjectAlreadyExistsException | CommunicationException - | ConfigurationException | SecurityViolationException e) { - throw new SystemException(e.getMessage(), e); - } - return true; - } - }; - display("Reconciling all orgs"); - modelService.searchObjectsIterative(OrgType.class, null, handler, null, task, result); - } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestScience.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestScience.java index f2a5018b26a..d5c31e577f2 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestScience.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestScience.java @@ -39,12 +39,6 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -/** - * - * @author Katarina Valalikova - * - */ - @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestScience extends AbstractStoryTest { @@ -57,9 +51,6 @@ public class TestScience extends AbstractStoryTest { private static final File ROLE_STATISTICS_FILE = new File(TEST_DIR, "role-statistics.xml"); private static final String ROLE_STATISTICS_OID = "23d90f70-1924-419e-9beb-78a8bde6d261"; - private static final File ROLE_MATH_FILE = new File(TEST_DIR, "role-math.xml"); - private static final String ROLE_MATH_OID = ""; - private static final File GROUP_STATS_USERS_LDIF_FILE = new File(TEST_DIR, "group-stats.ldif"); private static final File RESOURCE_OPENDJ_AD_SIMULATION_FILE = new File(TEST_DIR, "resource-opendj-ad-simulation.xml"); @@ -105,7 +96,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -152,7 +143,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; Task task = getTestTask(); OperationResult testResultStats = modelService.testResource(RESOURCE_DUMMY_STATS_OID, task); @@ -170,7 +160,6 @@ public void test000Sanity() throws Exception { @Test public void test100JackAssignRoleStatistics() throws Exception { - final String TEST_NAME = "test100JackAssignRoleStatistics"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -218,7 +207,6 @@ public void test100JackAssignRoleStatistics() throws Exception { @Test public void test101UnassignRoleStats() throws Exception{ - final String TEST_NAME = "test101UnassignRoleStats"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -269,7 +257,6 @@ public void test101UnassignRoleStats() throws Exception{ @Test public void test102AssignRoleStats() throws Exception{ - final String TEST_NAME = "test102AssignRoleStats"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -316,7 +303,6 @@ public void test102AssignRoleStats() throws Exception{ @Test public void test200DelteUserJack() throws Exception { - final String TEST_NAME = "test200DelteUserJack"; Task task = getTestTask(); OperationResult result = task.getResult(); diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccounts.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccounts.java index faadfa0a273..aa7f246ef52 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccounts.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccounts.java @@ -7,17 +7,9 @@ package com.evolveum.midpoint.testing.story; import static com.evolveum.midpoint.prism.util.PrismTestUtil.getPrismContext; -import static org.testng.Assert.assertEquals; -import static org.testng.Assert.assertFalse; -import static org.testng.Assert.assertNotEquals; -import static org.testng.Assert.assertNull; -import static org.testng.Assert.assertTrue; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; import java.io.File; -import com.evolveum.midpoint.prism.*; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -25,20 +17,22 @@ import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.icf.dummy.resource.DummySyncStyle; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.PrismReferenceValue; import com.evolveum.midpoint.prism.delta.ObjectDelta; import com.evolveum.midpoint.prism.delta.ReferenceDelta; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.task.api.TaskExecutionStatus; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.MidPointTestConstants; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.xml.ns._public.common.common_3.ServiceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestServiceAccounts extends AbstractStoryTest { @@ -46,7 +40,6 @@ public class TestServiceAccounts extends AbstractStoryTest { protected static final File RESOURCE_DUMMY_FILE = new File(TEST_DIR, "resource-dummy.xml"); protected static final String RESOURCE_DUMMY_OID = "0069ac14-8377-11e8-b404-5b5a1a8af0db"; - private static final String RESOURCE_DUMMY_NS = MidPointConstants.NS_RI; protected static final String RESOURCE_DUMMY_INTENT_SERVICE = "service"; private static final String ACCOUNT_RUM_STORAGE_DUMMY_USERNAME = "rum-storage"; @@ -58,9 +51,7 @@ public class TestServiceAccounts extends AbstractStoryTest { private static final String SERVICE_BARELLIUM_DESCRIPTION = "Barellium Superiorum"; private static final File ACCOUNT_BARELLIUM_DUMMY_FILE = new File(TEST_DIR, "account-barellium-dummy.xml"); - private static final String ACCOUNT_BARELLIUM_DUMMY_OID = "fe0d6d9a-a77d-11e8-a144-0bbeb63fd26b"; private static final String ACCOUNT_BARELLIUM_DUMMY_USERNAME = "barellium"; - private static final String ACCOUNT_BARELLIUM_DUMMY_FULLNAME = "Barellium Magnum"; private static final String ACCOUNT_MAGAZINE_DUMMY_USERNAME = "magazine"; private static final String ACCOUNT_MAGAZINE_DUMMY_FULLNAME = "Gunpowder magazine"; @@ -83,8 +74,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test100StartSyncTask() throws Exception { - final String TEST_NAME = "test100StartSyncTask"; - assertUsers(getNumberOfUsers()); assertServices(0); @@ -104,8 +93,6 @@ public void test100StartSyncTask() throws Exception { @Test public void test101AddServiceAccountSync() throws Exception { - final String TEST_NAME = "test101AddServiceAccountSync"; - // Preconditions assertServices(0); @@ -127,17 +114,17 @@ public void test101AddServiceAccountSync() throws Exception { assertServices(1); serviceAccountShadowOid = assertServiceAfterByName(ACCOUNT_RUM_STORAGE_DUMMY_USERNAME) - .assertDescription(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME) - .links() + .assertDescription(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME) + .links() .single() - .resolveTarget() - .assertLife() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(RESOURCE_DUMMY_INTENT_SERVICE) - .getOid(); + .resolveTarget() + .assertLife() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(RESOURCE_DUMMY_INTENT_SERVICE) + .getOid(); assertDummyAccountByUsername(null, ACCOUNT_RUM_STORAGE_DUMMY_USERNAME) - .assertFullName(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME); + .assertFullName(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME); } /** @@ -147,8 +134,6 @@ public void test101AddServiceAccountSync() throws Exception { */ @Test public void test102ModifyServiceAccount() throws Exception { - final String TEST_NAME = "test102ModifyServiceAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -175,17 +160,17 @@ serviceAccountShadowOid, getDummyResourceController().getAttributeFullnamePath() assertServices(1); assertServiceAfterByName(ACCOUNT_RUM_STORAGE_DUMMY_USERNAME) - .assertDescription(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME) - .links() + .assertDescription(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME) + .links() .single() - .resolveTarget() - .assertLife() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(RESOURCE_DUMMY_INTENT_SERVICE) - .getOid(); + .resolveTarget() + .assertLife() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(RESOURCE_DUMMY_INTENT_SERVICE) + .getOid(); assertDummyAccountByUsername(null, ACCOUNT_RUM_STORAGE_DUMMY_USERNAME) - .assertFullName(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME); + .assertFullName(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME); } /** @@ -195,8 +180,6 @@ serviceAccountShadowOid, getDummyResourceController().getAttributeFullnamePath() */ @Test public void test104DeleteServiceAccount() throws Exception { - final String TEST_NAME = "test104DeleteServiceAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -222,17 +205,17 @@ public void test104DeleteServiceAccount() throws Exception { assertServices(1); assertServiceAfterByName(ACCOUNT_RUM_STORAGE_DUMMY_USERNAME) - .assertDescription(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME) - .links() + .assertDescription(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME) + .links() .single() - .resolveTarget() - .assertLife() - .assertKind(ShadowKindType.ACCOUNT) - .assertIntent(RESOURCE_DUMMY_INTENT_SERVICE) - .getOid(); + .resolveTarget() + .assertLife() + .assertKind(ShadowKindType.ACCOUNT) + .assertIntent(RESOURCE_DUMMY_INTENT_SERVICE) + .getOid(); assertDummyAccountByUsername(null, ACCOUNT_RUM_STORAGE_DUMMY_USERNAME) - .assertFullName(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME); + .assertFullName(ACCOUNT_RUM_STORAGE_DUMMY_FULLNAME); } // TODO: account modifications, check that the changes are synced to service @@ -242,8 +225,6 @@ public void test104DeleteServiceAccount() throws Exception { */ @Test public void test108DeleteServiceAccountSync() throws Exception { - final String TEST_NAME = "test108DeleteServiceAccountSync"; - // Preconditions assertServices(1); @@ -263,8 +244,6 @@ public void test108DeleteServiceAccountSync() throws Exception { @Test public void test109StopLivesyncTask() throws Exception { - final String TEST_NAME = "test109StopLivesyncTask"; - // Preconditions assertServices(0); @@ -280,8 +259,6 @@ public void test109StopLivesyncTask() throws Exception { @Test public void test120StartReconTask() throws Exception { - final String TEST_NAME = "test120StartReconTask"; - assertUsers(getNumberOfUsers()); assertServices(0); @@ -301,8 +278,6 @@ public void test120StartReconTask() throws Exception { @Test public void test121AddServiceAccountRecon() throws Exception { - final String TEST_NAME = "test121AddServiceAccountRecon"; - // Preconditions assertServices(0); @@ -324,7 +299,7 @@ public void test121AddServiceAccountRecon() throws Exception { assertServices(1); assertServiceAfterByName(ACCOUNT_MAGAZINE_DUMMY_USERNAME) - .assertDescription(ACCOUNT_MAGAZINE_DUMMY_FULLNAME); + .assertDescription(ACCOUNT_MAGAZINE_DUMMY_FULLNAME); } /** @@ -332,8 +307,6 @@ public void test121AddServiceAccountRecon() throws Exception { */ @Test public void test128DeleteServiceAccountRecon() throws Exception { - final String TEST_NAME = "test128DeleteServiceAccountRecon"; - // Preconditions assertServices(1); @@ -351,9 +324,8 @@ public void test128DeleteServiceAccountRecon() throws Exception { assertServices(0); } + @UnusedTestElement public void test129StopReconTask() throws Exception { - final String TEST_NAME = "test129StopReconTask"; - // Preconditions assertServices(1); @@ -364,6 +336,7 @@ public void test129StopReconTask() throws Exception { // THEN then(); + assertTaskExecutionStatus(TASK_RECONCILE_DUMMY_OID, TaskExecutionStatus.SUSPENDED); } @@ -374,8 +347,6 @@ public void test129StopReconTask() throws Exception { */ @Test public void test140CreateServiceAccount() throws Exception { - final String TEST_NAME = "test140CreateServiceAccount"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -410,9 +381,9 @@ public void test140CreateServiceAccount() throws Exception { assertServices(1); assertServiceAfter(SERVICE_BARELLIUM_OID) - .assertName(SERVICE_BARELLIUM_NAME) - .assertDescription(SERVICE_BARELLIUM_DESCRIPTION) - .assertLinks(0); + .assertName(SERVICE_BARELLIUM_NAME) + .assertDescription(SERVICE_BARELLIUM_DESCRIPTION) + .assertLinks(0); assertNoDummyAccount(ACCOUNT_BARELLIUM_DUMMY_USERNAME); } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java index cfbea40d5c6..de3cf868dcd 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestServiceAccountsClassifier.java @@ -10,10 +10,8 @@ import static org.testng.AssertJUnit.assertNotNull; import java.io.File; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.prism.path.ItemPath; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; @@ -22,8 +20,8 @@ import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.icf.dummy.resource.DummySyncStyle; import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.prism.path.ItemPath; import com.evolveum.midpoint.prism.util.PrismAsserts; -import com.evolveum.midpoint.schema.constants.MidPointConstants; import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.asserter.ShadowAsserter; @@ -32,7 +30,7 @@ import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestServiceAccountsClassifier extends AbstractStoryTest { @@ -40,7 +38,6 @@ public class TestServiceAccountsClassifier extends AbstractStoryTest { protected static final File RESOURCE_DUMMY_CLASSIFIER_FILE = new File(TEST_DIR, "resource-dummy-classifier.xml"); protected static final String RESOURCE_DUMMY_CLASSIFIER_OID = "1169ac14-8377-11e8-b404-5b5a1a8af0db"; - private static final String RESOURCE_DUMMY_CLASSIFIER_NS = MidPointConstants.NS_RI; private static final File ROLE_EMPLOYEE_FILE = new File(TEST_DIR, "role-employee.xml"); private static final String ROLE_EMPLOYEE_OID = "23d90f70-1924-419e-9beb-78a8bde6d261"; @@ -77,9 +74,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti } @Test - public void test001assigneJackEmployeeRole() throws Exception { - final String TEST_NAME = "test001assigneJackEmployeeRole"; - + public void test001assignJackEmployeeRole() throws Exception { //WHEN when(); assignRole(USER_JACK_OID, ROLE_EMPLOYEE_OID); @@ -93,8 +88,6 @@ public void test001assigneJackEmployeeRole() throws Exception { @Test public void test100createServiceJira() throws Exception { - final String TEST_NAME = "test100createServiceJira"; - //WHEN addObject(SERVICE_JIRA_FILE); @@ -109,7 +102,6 @@ public void test100createServiceJira() throws Exception { @Test public void test101jiraAssignResourceNoneEnforcement() throws Exception { - final String TEST_NAME = "test101jiraAssignResourceNoneEnforcement"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -131,8 +123,6 @@ public void test101jiraAssignResourceNoneEnforcement() throws Exception { @Test public void test150StartReconTask() throws Exception { - final String TEST_NAME = "test150StartReconTask"; - assertUsers(getNumberOfUsers()); assertServices(1); @@ -152,8 +142,6 @@ public void test150StartReconTask() throws Exception { @Test public void test151LinkServiceAccountRecon() throws Exception { - final String TEST_NAME = "test151LinkServiceAccountRecon"; - // Preconditions assertServices(1); @@ -171,18 +159,17 @@ public void test151LinkServiceAccountRecon() throws Exception { then(); assertServices(1); - PrismObject serviceJirafter = getObject(ServiceType.class, SERVICE_JIRA_OID); - display("Service magazine after", serviceJirafter); - assertNotNull("No magazine service", serviceJirafter); - PrismAsserts.assertPropertyValue(serviceJirafter, ItemPath.create(ServiceType.F_EXTENSION, F_ACCOUNT_NAME), ACCOUNT_DUMMY_JIRA_USERNAME); - assertLinks(serviceJirafter, 1); + PrismObject serviceJiraAfter = getObject(ServiceType.class, SERVICE_JIRA_OID); + display("Service magazine after", serviceJiraAfter); + assertNotNull("No magazine service", serviceJiraAfter); + PrismAsserts.assertPropertyValue(serviceJiraAfter, + ItemPath.create(ServiceType.F_EXTENSION, F_ACCOUNT_NAME), ACCOUNT_DUMMY_JIRA_USERNAME); + assertLinks(serviceJiraAfter, 1); } @Test public void test152InactivateUnmatchedAccountRecon() throws Exception { - final String TEST_NAME = "test152InactivateUnmatchedAccountRecon"; - // Preconditions assertServices(1); @@ -207,8 +194,6 @@ public void test152InactivateUnmatchedAccountRecon() throws Exception { @Test public void test200createServiceGithub() throws Exception { - final String TEST_NAME = "test200createServiceGithub"; - //WHEN addObject(SERVICE_GITHUB_FILE); @@ -223,8 +208,6 @@ public void test200createServiceGithub() throws Exception { @Test public void test210createAccountGithub() throws Exception { - final String TEST_NAME = "test210createAccountGithub"; - //WHEN when(); addObject(SHADOW_GITHUB_FILE); @@ -242,7 +225,6 @@ public void test210createAccountGithub() throws Exception { @Test public void test215githubAssignResourceNoneEnforcement() throws Exception { - final String TEST_NAME = "test101jiraAssignResourceNoneEnforcement"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -264,7 +246,6 @@ public void test215githubAssignResourceNoneEnforcement() throws Exception { @Test public void test220linkAccountGithubAndFixIntent() throws Exception { - final String TEST_NAME = "test220linkAccountGithubAndFixIntent"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -296,6 +277,4 @@ public void test220linkAccountGithubAndFixIntent() throws Exception { ShadowAsserter.forShadow(shadowGithub).assertIntent("service"); } - - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestShadowsPerformance.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestShadowsPerformance.java index c4d16a6485b..a105b9b609b 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestShadowsPerformance.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestShadowsPerformance.java @@ -27,12 +27,14 @@ import com.evolveum.midpoint.test.DummyAuditService; import com.evolveum.midpoint.test.DummyResourceContoller; import com.evolveum.midpoint.test.util.MidPointTestConstants; +import com.evolveum.midpoint.tools.testng.UnusedTestElement; import com.evolveum.midpoint.xml.ns._public.common.common_3.OperationStatsType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; /** * Tests creation and deletion of shadows. */ +@UnusedTestElement("Not in suite, test210 fails") @ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestShadowsPerformance extends AbstractStoryTest { @@ -97,8 +99,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test010Sanity() throws Exception { - final String TEST_NAME = "test010Sanity"; - Task task = getTestTask(); // WHEN @@ -113,8 +113,6 @@ public void test010Sanity() throws Exception { @Test public void test100ImportAccounts() throws Exception { - final String TEST_NAME = "test100ImportAccounts"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -135,7 +133,7 @@ public void test100ImportAccounts() throws Exception { display("task after", prismContext.xmlSerializer().serialize(taskAfter.getUpdatedTaskObject())); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_IMPORT_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); int shadows = repositoryService.countObjects(ShadowType.class, null, null, result); @@ -144,8 +142,6 @@ public void test100ImportAccounts() throws Exception { @Test(enabled = false) public void test200DeleteAccountsAndReconcile() throws Exception { - final String TEST_NAME = "test200DeleteAccountsAndReconcile"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -165,7 +161,7 @@ public void test200DeleteAccountsAndReconcile() throws Exception { display("task after", prismContext.xmlSerializer().serialize(taskAfter.getUpdatedTaskObject())); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_RECONCILIATION_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); int shadows = repositoryService.countObjects(ShadowType.class, null, null, result); @@ -174,8 +170,6 @@ public void test200DeleteAccountsAndReconcile() throws Exception { @Test public void test210DeleteShadows() throws Exception { - final String TEST_NAME = "test210DeleteShadows"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -195,7 +189,7 @@ public void test210DeleteShadows() throws Exception { display("task after", prismContext.xmlSerializer().serialize(taskAfter.getUpdatedTaskObject())); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_BULK_DELETE_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); int shadows = repositoryService.countObjects(ShadowType.class, null, null, result); @@ -204,11 +198,6 @@ public void test210DeleteShadows() throws Exception { @Test public void test900Summarize() { - final String TEST_NAME = "test900Summarize"; - - Task task = getTestTask(); - OperationResult result = task.getResult(); - StringBuilder sb = new StringBuilder(); for (Map.Entry entry : durations.entrySet()) { sb.append(summary(entry.getKey(), entry.getValue())); @@ -222,6 +211,7 @@ public void test900Summarize() { } + // TODO use it or let it go :-) private long recordDuration(String label, long duration) { durations.put(label, duration); return duration; @@ -230,5 +220,4 @@ private long recordDuration(String label, long duration) { private Object summary(String label, long duration) { return String.format(SUMMARY_LINE_FORMAT, label, duration, duration / NUMBER_OF_GENERATED_USERS); } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java index c96f660fc57..955708958b4 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestStrings.java @@ -51,16 +51,9 @@ import com.evolveum.midpoint.schema.util.ApprovalContextUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.util.DebugUtil; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.wf.util.ApprovalUtils; -/** - * - * @author mederly - * - */ - @SuppressWarnings("FieldCanBeLocal") @ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @@ -129,11 +122,8 @@ public class TestStrings extends AbstractStoryTest { private static final File CONFIG_WITH_GLOBAL_RULES_FILE = new File(ROLES_DIR, "global-policy-rules.xml"); - public static final String NS_STRINGS_EXT = "http://midpoint.evolveum.com/xml/ns/strings"; - private static final String DUMMY_WORK_ITEM_LIFECYCLE = "dummy:workItemLifecycle"; private static final String DUMMY_WORK_ITEM_ALLOCATION = "dummy:workItemAllocation"; - private static final String DUMMY_WORK_ITEM_CUSTOM = "dummy:workItemCustom"; private static final String DUMMY_PROCESS = "dummy:process"; protected static final int CASE_WAIT_TIMEOUT = 40000; @@ -196,16 +186,12 @@ protected PrismObject getDefaultActor() { @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = getTestTask(); - // TODO } //region Basic approval @Test public void test100SimpleAssignmentStart() throws Exception { - final String TEST_NAME = "test100SimpleAssignmentStart"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -270,7 +256,6 @@ public void test100SimpleAssignmentStart() throws Exception { @Test public void test102SimpleAssignmentApproveByLechuck() throws Exception { - final String TEST_NAME = "test102SimpleAssignmentApproveByLechuck"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -351,14 +336,13 @@ public void test102SimpleAssignmentApproveByLechuck() throws Exception { // events List events = assertEvents(aCase, 2); - assertCompletionEvent(events.get(1), userLechuckOid, userLechuckOid, 1, "Line managers", WorkItemOutcomeType.APPROVE, "OK. LeChuck"); + assertCompletionEvent(events.get(1), userLechuckOid, userLechuckOid, 1, WorkItemOutcomeType.APPROVE, "OK. LeChuck"); display("audit", dummyAuditService); } @Test public void test104SimpleAssignmentApproveByAdministrator() throws Exception { - final String TEST_NAME = "test104SimpleAssignmentApproveByAdministrator"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -438,7 +422,6 @@ public void test104SimpleAssignmentApproveByAdministrator() throws Exception { @Test public void test106SimpleAssignmentApproveByCheese() throws Exception { - final String TEST_NAME = "test106SimpleAssignmentApproveByCheese"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -496,7 +479,6 @@ public void test106SimpleAssignmentApproveByCheese() throws Exception { @Test public void test108SimpleAssignmentApproveByChef() throws Exception { - final String TEST_NAME = "test108SimpleAssignmentApproveByChef"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -573,7 +555,6 @@ public void test108SimpleAssignmentApproveByChef() throws Exception { //region Testing escalation @Test public void test200EscalatedApprovalStart() throws Exception { - final String TEST_NAME = "test200EscalatedApprovalStart"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -620,10 +601,6 @@ public void test200EscalatedApprovalStart() throws Exception { @Test public void test202FourDaysLater() throws Exception { - final String TEST_NAME = "test202FourDaysLater"; - Task task = getTestTask(); - OperationResult result = task.getResult(); - dummyAuditService.clear(); dummyTransport.clearMessages(); @@ -652,7 +629,6 @@ public void test202FourDaysLater() throws Exception { // escalation should occur here @Test public void test204SixDaysLater() throws Exception { - final String TEST_NAME = "test204SixDaysLater"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -689,7 +665,7 @@ public void test204SixDaysLater() throws Exception { assertEquals("Wrong escalation level name", "Line manager escalation", ApprovalContextUtil.getEscalationLevelName(workItem)); List events = assertEvents(aCase, 2); - assertEscalationEvent(events.get(1), userAdministrator.getOid(), userGuybrushOid, 1, "Line managers", + assertEscalationEvent(events.get(1), userAdministrator.getOid(), userGuybrushOid, 1, Collections.singletonList(userGuybrushOid), Collections.singletonList(userCheeseOid), WorkItemDelegationMethodType.ADD_ASSIGNEES, 1, "Line manager escalation"); @@ -719,10 +695,6 @@ public void test204SixDaysLater() throws Exception { @Test public void test205EightDaysLater() throws Exception { - final String TEST_NAME = "test205EightDaysLater"; - Task task = getTestTask(); - OperationResult result = task.getResult(); - dummyAuditService.clear(); dummyTransport.clearMessages(); @@ -770,7 +742,6 @@ public void test205EightDaysLater() throws Exception { @Test public void test206ApproveByCheese() throws Exception { - final String TEST_NAME = "test206ApproveByCheese"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -863,7 +834,6 @@ public void test206ApproveByCheese() throws Exception { // notification should be send @Test public void test208SixDaysLater() throws Exception { - final String TEST_NAME = "test208SixDaysLater"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -904,10 +874,6 @@ public void test208SixDaysLater() throws Exception { @Test public void test209EightDaysLater() throws Exception { - final String TEST_NAME = "test209EightDaysLater"; - Task task = getTestTask(); - OperationResult result = task.getResult(); - dummyAuditService.clear(); dummyTransport.clearMessages(); @@ -947,7 +913,6 @@ private void checkTwoCompleted(List lifecycleMessages) { assertMessage(sorted.get("barkeeper@evolveum.com"), "barkeeper@evolveum.com", null, "Security (2/3)", "Allocated to: Horridly Scarred Barkeep (barkeeper)"); - int completed; assertMessage(lifecycleMessages.get(0), null, "Work item has been completed", "^Carried out by:", "Reason: Timed action", @@ -960,7 +925,6 @@ private void checkTwoCompleted(List lifecycleMessages) { @Test public void test220FormRoleAssignmentStart() throws Exception { - final String TEST_NAME = "test220FormRoleAssignmentStart"; PrismObject bob = getUserFromRepo(userBobOid); login(bob); @@ -1004,7 +968,6 @@ public void test220FormRoleAssignmentStart() throws Exception { @Test public void test221FormApproveByLechuck() throws Exception { - final String TEST_NAME = "test221FormApproveByLechuck"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1049,7 +1012,6 @@ public void test221FormApproveByLechuck() throws Exception { @Test public void test222FormApproveByCheese() throws Exception { - final String TEST_NAME = "test222FormApproveByCheese"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1119,7 +1081,6 @@ public void test222FormApproveByCheese() throws Exception { @Test public void test250ApproverAssignment() throws Exception { - final String TEST_NAME = "test250ApproverAssignment"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1204,11 +1165,6 @@ private Map sortByRecipientsSingle(Collection messages return rv; } - private Task getParentTask(PrismObject task, OperationResult result) - throws SchemaException, ObjectNotFoundException { - return taskManager.getTaskByIdentifier(task.asObjectable().getParent(), result); - } - private void assertTriggers(CaseType aCase, int count) { assertEquals("Wrong # of triggers", count, aCase.getTrigger().size()); } @@ -1241,13 +1197,13 @@ private List assertEvents(CaseType aCase, int expectedCount) { } private void assertEscalationEvent(CaseEventType wfProcessEventType, String initiator, String originalAssignee, - int stageNumber, String stageName, List assigneesBefore, List delegatedTo, + int stageNumber, List assigneesBefore, List delegatedTo, WorkItemDelegationMethodType methodType, int newEscalationLevelNumber, String newEscalationLevelName) throws SchemaException { if (!(wfProcessEventType instanceof WorkItemEscalationEventType)) { fail("Wrong event class: expected: " + WorkItemEscalationEventType.class + ", real: " + wfProcessEventType.getClass()); } WorkItemEscalationEventType event = (WorkItemEscalationEventType) wfProcessEventType; - assertEvent(event, initiator, originalAssignee, stageNumber, stageName); + assertEvent(event, initiator, originalAssignee, stageNumber); PrismAsserts.assertReferenceValues(ref(event.getAssigneeBefore()), assigneesBefore.toArray(new String[0])); PrismAsserts.assertReferenceValues(ref(event.getDelegatedTo()), delegatedTo.toArray(new String[0])); assertEquals("Wrong delegation method", methodType, event.getDelegationMethod()); @@ -1256,18 +1212,18 @@ private void assertEscalationEvent(CaseEventType wfProcessEventType, String init } private void assertCompletionEvent(CaseEventType wfProcessEventType, String initiator, String originalAssignee, - int stageNumber, String stageName, WorkItemOutcomeType outcome, String comment) throws SchemaException { + int stageNumber, WorkItemOutcomeType outcome, String comment) throws SchemaException { if (!(wfProcessEventType instanceof WorkItemCompletionEventType)) { fail("Wrong event class: expected: " + WorkItemCompletionEventType.class + ", real: " + wfProcessEventType.getClass()); } WorkItemCompletionEventType event = (WorkItemCompletionEventType) wfProcessEventType; - assertEvent(event, initiator, originalAssignee, stageNumber, stageName); + assertEvent(event, initiator, originalAssignee, stageNumber); assertEquals("Wrong outcome", outcome, ApprovalUtils.fromUri(event.getOutput().getOutcome())); assertEquals("Wrong comment", comment, event.getOutput().getComment()); } - private void assertEvent(CaseEventType processEvent, String initiator, String originalAssignee, Integer stageNumber, - String stageName) throws SchemaException { + private void assertEvent(CaseEventType processEvent, + String initiator, String originalAssignee, Integer stageNumber) throws SchemaException { if (!(processEvent instanceof WorkItemEventType)) { fail("Wrong event class: expected: " + WorkItemEventType.class + ", real: " + processEvent.getClass()); } @@ -1280,5 +1236,4 @@ private void assertEvent(CaseEventType processEvent, String initiator, String or PrismAsserts.assertReferenceValue(ref(event.getOriginalAssigneeRef()), originalAssignee); } } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUniversity.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUniversity.java index 1b7f34b5261..578e5a7c241 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUniversity.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUniversity.java @@ -7,6 +7,19 @@ package com.evolveum.midpoint.testing.story; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; +import javax.xml.namespace.QName; + +import org.opends.server.types.DirectoryException; +import org.opends.server.types.Entry; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.AfterClass; +import org.testng.annotations.Test; import com.evolveum.icf.dummy.resource.DummyObjectClass; import com.evolveum.icf.dummy.resource.DummyPrivilege; @@ -20,40 +33,20 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.DummyResourceContoller; +import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; -import com.evolveum.midpoint.util.exception.CommunicationException; -import com.evolveum.midpoint.util.exception.ConfigurationException; -import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; -import com.evolveum.midpoint.util.exception.ObjectNotFoundException; -import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.util.exception.SecurityViolationException; +import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.OrgType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import org.opends.server.types.DirectoryException; -import org.opends.server.types.Entry; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; - -import javax.xml.namespace.QName; - -import java.io.File; - -import static org.testng.AssertJUnit.assertNotNull; - /** * @author Radovan Semancik * @author mederly - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUniversity extends AbstractStoryTest { @@ -69,7 +62,6 @@ public class TestUniversity extends AbstractStoryTest { protected static final File RESOURCE_OPENDJ_FILE = new File(TEST_DIR, "resource-opendj.xml"); protected static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; protected static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - protected static final QName OPENDJ_ASSOCIATION_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "group"); private static final String DUMMY_PRIVILEGE_ATTRIBUTE_HR_ORGPATH = "orgpath"; @@ -82,21 +74,9 @@ public class TestUniversity extends AbstractStoryTest { protected static final File TASK_LIVE_SYNC_DUMMY_HR_FILE = new File(TEST_DIR, "task-dummy-hr-livesync.xml"); protected static final String TASK_LIVE_SYNC_DUMMY_HR_OID = "10000000-0000-0000-5555-555500000001"; - protected static final File TASK_RECON_OPENDJ_DEFAULT_SINGLE_FILE = new File(TEST_DIR, "task-reconcile-opendj-default-single.xml"); - protected static final String TASK_RECON_OPENDJ_DEFAULT_SINGLE_OID = "10000000-0000-0000-5555-555500000004"; - - protected static final File TASK_RECON_OPENDJ_LDAPGROUP_SINGLE_FILE = new File(TEST_DIR, "task-reconcile-opendj-ldapgroup-single.xml"); - protected static final String TASK_RECON_OPENDJ_LDAPGROUP_SINGLE_OID = "10000000-0000-0000-5555-555500000014"; - - private static final File SCABB_OU_LDIF_FILE = new File(TEST_DIR, "scabb.ldif"); - private static final File BOOTY_OU_LDIF_FILE = new File(TEST_DIR, "booty.ldif"); - private static final File BOOTY_LOOKOUT_OU_LDIF_FILE = new File(TEST_DIR, "booty-lookout.ldif"); - @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; - private DebugReconciliationTaskResultListener reconciliationTaskResultListener; - protected static DummyResource dummyResourceHr; protected static DummyResourceContoller dummyResourceCtlHr; protected ResourceType resourceDummyHrType; @@ -124,7 +104,7 @@ public static void stopResources() { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); + DebugReconciliationTaskResultListener reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); reconciliationTaskHandler.setReconciliationTaskResultListener(reconciliationTaskResultListener); // Resources @@ -141,11 +121,6 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti resourceOpenDjType = resourceOpenDj.asObjectable(); openDJController.setResource(resourceOpenDj); -// // LDAP content -// openDJController.addEntryFromLdifFile(SCABB_OU_LDIF_FILE); -// openDJController.addEntryFromLdifFile(BOOTY_OU_LDIF_FILE); -// openDJController.addEntryFromLdifFile(BOOTY_LOOKOUT_OU_LDIF_FILE); -// // Object Templates importObjectFromFile(OBJECT_TEMPLATE_ORG_FILE, initResult); setDefaultObjectTemplate(OrgType.COMPLEX_TYPE, OBJECT_TEMPLATE_ORG_OID); @@ -162,8 +137,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestUniversity.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_HR_OID, task); TestUtil.assertSuccess(testResultHr); @@ -178,8 +152,6 @@ public void test000Sanity() throws Exception { @Test public void test100AddComeniusUniversity() throws Exception { - final String TEST_NAME = "test100AddComeniusUniversity"; - DummyPrivilege comenius = new DummyPrivilege("UK"); // WHEN @@ -201,8 +173,6 @@ public void test100AddComeniusUniversity() throws Exception { @Test public void test110AddComeniusStructure() throws Exception { - final String TEST_NAME = "test110AddComeniusStructure"; - DummyPrivilege srcFmfi = new DummyPrivilege("FMFI"); srcFmfi.addAttributeValue(DUMMY_PRIVILEGE_ATTRIBUTE_HR_ORGPATH, "UK"); @@ -271,11 +241,8 @@ private void assertNoGroupMembers(PrismObject org) throws Exception { assertNoAttribute(groupShadow.asObjectable(), new QName(MidPointConstants.NS_RI, "uniqueMember")); } - @Test public void test120MoveComputingCentre() throws Exception { - final String TEST_NAME = "test120MoveComputingCentre"; - DummyPrivilege srcVc = dummyResourceHr.getPrivilegeByName("VC"); // WHEN @@ -335,18 +302,18 @@ private PrismObject getAndAssertFunctionalOrg(String orgName) throws Sc String groupOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, "org-group"); PrismObject groupShadow = getShadowModel(groupOid); - display("Org "+orgName+" group shadow", groupShadow); + display("Org " + orgName + " group shadow", groupShadow); // TODO assert shadow content - Entry ouEntry = openDJController.searchSingle("ou="+orgName); - assertNotNull("No ou LDAP entry for "+orgName, ouEntry); + Entry ouEntry = openDJController.searchSingle("ou=" + orgName); + assertNotNull("No ou LDAP entry for " + orgName, ouEntry); display("OU entry", ouEntry); - openDJController.assertObjectClass(ouEntry, "organizationalUnit"); + OpenDJController.assertObjectClass(ouEntry, "organizationalUnit"); - Entry groupEntry = openDJController.searchSingle("cn=DL-"+orgName); - assertNotNull("No group LDAP entry for "+orgName, groupEntry); + Entry groupEntry = openDJController.searchSingle("cn=DL-" + orgName); + assertNotNull("No group LDAP entry for " + orgName, groupEntry); display("OU GROUP entry", groupEntry); - openDJController.assertObjectClass(groupEntry, "groupOfUniqueNames"); + OpenDJController.assertObjectClass(groupEntry, "groupOfUniqueNames"); return org; } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnix.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnix.java index 142f64003b6..1c6c00f45c9 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnix.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnix.java @@ -6,15 +6,10 @@ */ package com.evolveum.midpoint.testing.story; -import static org.testng.AssertJUnit.assertEquals; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; +import static org.testng.AssertJUnit.*; import java.io.File; import java.util.List; - import javax.xml.datatype.XMLGregorianCalendar; import javax.xml.namespace.QName; @@ -55,31 +50,20 @@ import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.task.api.Task; import com.evolveum.midpoint.test.IntegrationTestTools; +import com.evolveum.midpoint.test.ldap.OpenDJController; import com.evolveum.midpoint.test.util.MidPointTestConstants; import com.evolveum.midpoint.test.util.TestUtil; import com.evolveum.midpoint.util.DOMUtil; import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.ExpressionEvaluationException; import com.evolveum.midpoint.util.exception.SchemaException; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationStatusType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ActivationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AssignmentType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.AuthorizationPhaseType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ObjectReferenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ResourceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.RoleType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.SequenceType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowAssociationType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowKindType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; -import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.*; import com.evolveum.prism.xml.ns._public.types_3.PolyStringType; /** * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestUnix extends AbstractStoryTest { @@ -170,46 +154,14 @@ public class TestUnix extends AbstractStoryTest { public static final String SEQUENCE_UIDNUMBER_OID = "7d4acb8c-65e3-11e5-9ef4-6382ba96fe6c"; public static final File SEQUENCE_GIDNUMBER_FILE = new File(TEST_DIR, "sequence-gidnumber.xml"); - public static final String SEQUENCE_GIDNUMBER_OID = "02cb7caa-6618-11e5-87a5-7b6c6776a63e"; protected static final String USER_STAN_USERNAME = "stan"; protected static final String USER_STAN_FIST_NAME = "Stan"; protected static final String USER_STAN_LAST_NAME = "Salesman"; - private static final String ACCOUNT_LEMONHEAD_USERNAME = "lemonhead"; - private static final String ACCOUNT_LEMONHEAD_FIST_NAME = "Lemonhead"; - private static final String ACCOUNT_LEMONHEAD_LAST_NAME = "Canibal"; - - private static final String ACCOUNT_SHARPTOOTH_USERNAME = "sharptooth"; - private static final String ACCOUNT_SHARPTOOTH_FIST_NAME = "Sharptooth"; - private static final String ACCOUNT_SHARPTOOTH_LAST_NAME = "Canibal"; - - private static final String ACCOUNT_REDSKULL_USERNAME = "redskull"; - private static final String ACCOUNT_REDSKULL_FIST_NAME = "Redskull"; - private static final String ACCOUNT_REDSKULL_LAST_NAME = "Canibal"; - - private static final String ACCOUNT_GUYBRUSH_USERNAME = "guybrush"; - private static final String ACCOUNT_GUYBRUSH_FIST_NAME = "Guybrush"; - private static final String ACCOUNT_GUYBRUSH_LAST_NAME = "Threepwood"; - - private static final String ACCOUNT_COBB_USERNAME = "cobb"; - private static final String ACCOUNT_COBB_FIST_NAME = "Cobb"; - private static final String ACCOUNT_COBB_LAST_NAME = "Loom"; - - private static final String ACCOUNT_STAN_USERNAME = "stan"; - private static final String ACCOUNT_STAN_FIST_NAME = "Stan"; - private static final String ACCOUNT_STAN_LAST_NAME = "Salesman"; - - private static final String ACCOUNT_AUGUSTUS_USERNAME = "augustus"; - private static final String ACCOUNT_AUGUSTUS_FIST_NAME = "Augustus"; - private static final String ACCOUNT_AUGUSTUS_LAST_NAME = "DeWaat"; - - - @Autowired(required=true) + @Autowired private ReconciliationTaskHandler reconciliationTaskHandler; - private DebugReconciliationTaskResultListener reconciliationTaskResultListener; - protected ResourceType resourceOpenDjType; protected PrismObject resourceOpenDj; @@ -246,7 +198,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -254,7 +206,7 @@ public static void stopResources() throws Exception { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); + DebugReconciliationTaskResultListener reconciliationTaskResultListener = new DebugReconciliationTaskResultListener(); reconciliationTaskHandler.setReconciliationTaskResultListener(reconciliationTaskResultListener); // Resources @@ -293,7 +245,6 @@ protected String getResourceOid() { @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; Task task = getTestTask(); OperationResult testResultOpenDj = modelService.testResource(getResourceOid(), task); @@ -305,8 +256,6 @@ public void test000Sanity() throws Exception { @Test public void test010Schema() throws Exception { - final String TEST_NAME = "test010Schema"; - resourceOpenDj = getObject(ResourceType.class, getResourceOid()); resourceOpenDjType = resourceOpenDj.asObjectable(); @@ -316,29 +265,28 @@ public void test010Schema() throws Exception { display("OpenDJ schema (resource)", resourceSchema); ObjectClassComplexTypeDefinition ocDefPosixAccount = resourceSchema.findObjectClassDefinition(OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME); - assertNotNull("No objectclass "+OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME+" in resource schema", ocDefPosixAccount); - assertTrue("Objectclass "+OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME+" is not auxiliary", ocDefPosixAccount.isAuxiliary()); + assertNotNull("No objectclass " + OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME + " in resource schema", ocDefPosixAccount); + assertTrue("Objectclass " + OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME + " is not auxiliary", ocDefPosixAccount.isAuxiliary()); ObjectClassComplexTypeDefinition ocDefPosixGroup = resourceSchema.findObjectClassDefinition(OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME); - assertNotNull("No objectclass "+OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME+" in resource schema", ocDefPosixGroup); - assertTrue("Objectclass "+OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME+" is not auxiliary", ocDefPosixGroup.isAuxiliary()); + assertNotNull("No objectclass " + OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME + " in resource schema", ocDefPosixGroup); + assertTrue("Objectclass " + OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME + " is not auxiliary", ocDefPosixGroup.isAuxiliary()); RefinedResourceSchema refinedSchema = RefinedResourceSchema.getRefinedSchema(resourceOpenDj); display("OpenDJ schema (refined)", refinedSchema); RefinedObjectClassDefinition rOcDefPosixAccount = refinedSchema.getRefinedDefinition(OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME); - assertNotNull("No refined objectclass "+OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME+" in resource schema", rOcDefPosixAccount); - assertTrue("Refined objectclass "+OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME+" is not auxiliary", rOcDefPosixAccount.isAuxiliary()); + assertNotNull("No refined objectclass " + OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME + " in resource schema", rOcDefPosixAccount); + assertTrue("Refined objectclass " + OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME + " is not auxiliary", rOcDefPosixAccount.isAuxiliary()); RefinedObjectClassDefinition rOcDefPosixGroup = refinedSchema.getRefinedDefinition(OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME); - assertNotNull("No refined objectclass "+OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME+" in resource schema", rOcDefPosixGroup); - assertTrue("Refined objectclass "+OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME+" is not auxiliary", rOcDefPosixGroup.isAuxiliary()); + assertNotNull("No refined objectclass " + OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME + " in resource schema", rOcDefPosixGroup); + assertTrue("Refined objectclass " + OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME + " is not auxiliary", rOcDefPosixGroup.isAuxiliary()); } @Test public void test100AddUserHermanBasic() throws Exception { - final String TEST_NAME = "test100AddUserHermanBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -365,7 +313,6 @@ public void test100AddUserHermanBasic() throws Exception { @Test public void test110AddUserMancombUnix() throws Exception { - final String TEST_NAME = "test110AddUserMancombUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -392,7 +339,6 @@ public void test110AddUserMancombUnix() throws Exception { @Test public void test111AccountMancombEditObjectClassDefinition() throws Exception { - final String TEST_NAME = "test111AccountMancombEditObjectClassDefinition"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -421,7 +367,6 @@ public void test111AccountMancombEditObjectClassDefinition() throws Exception { @Test public void test119DeleteUserMancombUnix() throws Exception { - final String TEST_NAME = "test119DeleteUserMancombUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -446,11 +391,10 @@ public void test119DeleteUserMancombUnix() throws Exception { @Test public void test120AddUserLargo() throws Exception { - final String TEST_NAME = "test120AddUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); - PrismObject user = createUser(USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, (String)null); + PrismObject user = createUser(USER_LARGO_USERNAME, USER_LARGO_FIST_NAME, USER_LARGO_LAST_NAME, (String) null); // WHEN when(); @@ -469,7 +413,6 @@ public void test120AddUserLargo() throws Exception { @Test public void test122AssignUserLargoBasic() throws Exception { - final String TEST_NAME = "test122AssignUserLargoBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -497,7 +440,6 @@ public void test122AssignUserLargoBasic() throws Exception { @Test public void test124AssignUserLargoUnix() throws Exception { - final String TEST_NAME = "test124AssignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -531,7 +473,6 @@ public void test124AssignUserLargoUnix() throws Exception { @Test public void test125RecomputeUserLargo() throws Exception { - final String TEST_NAME = "test125RecomputeUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -559,7 +500,6 @@ public void test125RecomputeUserLargo() throws Exception { @Test public void test126UnAssignUserLargoUnix() throws Exception { - final String TEST_NAME = "test126UnAssignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -587,7 +527,6 @@ public void test126UnAssignUserLargoUnix() throws Exception { @Test public void test127RecomputeUserLargo() throws Exception { - final String TEST_NAME = "test127RecomputeUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -615,7 +554,6 @@ public void test127RecomputeUserLargo() throws Exception { @Test public void test128UnAssignUserLargoBasic() throws Exception { - final String TEST_NAME = "test128UnAssignUserLargoBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -642,7 +580,6 @@ public void test128UnAssignUserLargoBasic() throws Exception { @Test public void test129RecomputeUserLargo() throws Exception { - final String TEST_NAME = "test129RecomputeUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -669,7 +606,6 @@ public void test129RecomputeUserLargo() throws Exception { @Test public void test130AssignUserLargoUnix() throws Exception { - final String TEST_NAME = "test130AssignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -697,7 +633,6 @@ public void test130AssignUserLargoUnix() throws Exception { @Test public void test131ReconcileUserLargo() throws Exception { - final String TEST_NAME = "test131ReconcileUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -736,26 +671,25 @@ public void test131ReconcileUserLargo() throws Exception { */ @Test public void test132MeddleWithAccountAndReconcileUserLargo() throws Exception { - final String TEST_NAME = "test132MeddleWithAccountAndReconcileUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); openDJController.executeLdifChange( - "dn: "+accountLargoDn+"\n"+ - "changetype: modify\n" + - "delete: objectClass\n" + - "objectClass: posixAccount\n" + - "-\n" + - "delete: homeDirectory\n" + - "homeDirectory: /home/largo\n" + - "-\n" + - "delete: uidNumber\n" + - "uidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + - "-\n" + - "delete: gidNumber\n" + - "gidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + "dn: " + accountLargoDn + "\n" + + "changetype: modify\n" + + "delete: objectClass\n" + + "objectClass: posixAccount\n" + + "-\n" + + "delete: homeDirectory\n" + + "homeDirectory: /home/largo\n" + + "-\n" + + "delete: uidNumber\n" + + "uidNumber: " + USER_LARGO_UID_NUMBER + "\n" + + "-\n" + + "delete: gidNumber\n" + + "gidNumber: " + USER_LARGO_UID_NUMBER + "\n" ); Entry entryBefore = openDJController.fetchEntry(accountLargoDn); @@ -803,7 +737,6 @@ protected void assertTest132Audit() { */ @Test public void test133ReconcileUserLargoAgain() throws Exception { - final String TEST_NAME = "test133ReconcileUserLargoAgain"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -841,7 +774,6 @@ public void test133ReconcileUserLargoAgain() throws Exception { @Test public void test134AssignUserLargoBasic() throws Exception { - final String TEST_NAME = "test134AssignUserLargoBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -877,7 +809,6 @@ public void test134AssignUserLargoBasic() throws Exception { @Test public void test135UnAssignUserLargoUnix() throws Exception { - final String TEST_NAME = "test135UnAssignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -922,26 +853,25 @@ protected void assertTest135Audit() { */ @Test // MID-2883 public void test136MeddleWithAccountAndReconcileUserLargo() throws Exception { - final String TEST_NAME = "test136MeddleWithAccountAndReconcileUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); openDJController.executeLdifChange( - "dn: "+accountLargoDn+"\n"+ - "changetype: modify\n" + - "add: objectClass\n" + - "objectClass: posixAccount\n" + - "-\n" + - "add: homeDirectory\n" + - "homeDirectory: /home/largo\n" + - "-\n" + - "add: uidNumber\n" + - "uidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + - "-\n" + - "add: gidNumber\n" + - "gidNumber: "+ USER_LARGO_UID_NUMBER +"\n" + "dn: " + accountLargoDn + "\n" + + "changetype: modify\n" + + "add: objectClass\n" + + "objectClass: posixAccount\n" + + "-\n" + + "add: homeDirectory\n" + + "homeDirectory: /home/largo\n" + + "-\n" + + "add: uidNumber\n" + + "uidNumber: " + USER_LARGO_UID_NUMBER + "\n" + + "-\n" + + "add: gidNumber\n" + + "gidNumber: " + USER_LARGO_UID_NUMBER + "\n" ); Entry entryBefore = openDJController.fetchEntry(accountLargoDn); @@ -981,7 +911,6 @@ protected void assertAccountTest136(PrismObject shadow) throws Excep */ @Test public void test137ReconcileUserLargoAgain() throws Exception { - final String TEST_NAME = "test137ReconcileUserLargoAgain"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1027,7 +956,6 @@ protected void assertTest137Account(PrismObject shadow) throws Excep @Test public void test138UnAssignUserLargoBasic() throws Exception { - final String TEST_NAME = "test138UnAssignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1056,7 +984,6 @@ public void test138UnAssignUserLargoBasic() throws Exception { @Test public void test200AddLdapGroupMonkeyIsland() throws Exception { - final String TEST_NAME = "test200AddLdapGroupMonkeyIsland"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1084,7 +1011,6 @@ public void test200AddLdapGroupMonkeyIsland() throws Exception { @Test public void test202AssignUserHermanMonkeyIsland() throws Exception { - final String TEST_NAME = "test202AssignUserHermanMonkeyIsland"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1112,7 +1038,6 @@ public void test202AssignUserHermanMonkeyIsland() throws Exception { @Test public void test210AddUnixGroupVillains() throws Exception { - final String TEST_NAME = "test210AddUnixGroupVillains"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1140,7 +1065,6 @@ public void test210AddUnixGroupVillains() throws Exception { @Test public void test211AssignUserLargoUnix() throws Exception { - final String TEST_NAME = "test211AssignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1168,7 +1092,6 @@ public void test211AssignUserLargoUnix() throws Exception { @Test public void test212AssignUserLargoVillains() throws Exception { - final String TEST_NAME = "test212AssignUserLargoVillains"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1192,13 +1115,12 @@ public void test212AssignUserLargoVillains() throws Exception { display("Shadow (model)", shadow); String accountLArgoDn = assertPosixAccount(shadow, USER_LARGO_UID_NUMBER); Entry groupVillains = openDJController.fetchEntry(groupVillainsDn); - openDJController.assertAttribute(groupVillains, "memberUid", USER_LARGO_USERNAME); + OpenDJController.assertAttribute(groupVillains, "memberUid", USER_LARGO_USERNAME); //openDJController.assertAttribute(groupVillains, "memberUid", Integer.toString(USER_LARGO_UID_NUMBER)); } @Test public void test250AddUserRangerBasic() throws Exception { - final String TEST_NAME = "test250AddUserRangerBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1225,7 +1147,6 @@ public void test250AddUserRangerBasic() throws Exception { @Test public void test251AssignUserRangerBasic() throws Exception { - final String TEST_NAME = "test251AssignUserRangerBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1253,7 +1174,6 @@ public void test251AssignUserRangerBasic() throws Exception { @Test public void test252AddUnixGroupRangers() throws Exception { - final String TEST_NAME = "test252AddUnixGroupRangers"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1281,7 +1201,6 @@ public void test252AddUnixGroupRangers() throws Exception { @Test public void test253AddUnixGroupSeals() throws Exception { - final String TEST_NAME = "test253AddUnixGroupSeals"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1311,7 +1230,6 @@ public void test253AddUnixGroupSeals() throws Exception { @Test public void test254AssignUserRangerRangers() throws Exception { - final String TEST_NAME = "test254AssignUserRangerRangers"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1337,22 +1255,21 @@ public void test254AssignUserRangerRangers() throws Exception { String accountRangerDn = assertPosixAccount(shadow, USER_RANGER_UID_NUMBER); Entry groupRangers = openDJController.fetchEntry(groupRangersDn); //openDJController.assertAttribute(groupRangers, "memberUid", Integer.toString(USER_RANGER_UID_NUMBER)); - openDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME); + OpenDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME); assertGroupAssociation(shadow, groupRangersOid); PrismObject repoShadow = provisioningService.getObject(ShadowType.class, accountOid, SelectorOptions.createCollection(GetOperationOptions.createNoFetch()), task, result); display("Shadow (repo)", repoShadow); //PrismProperty uidNumberRepoAttr = repoShadow.findProperty(prismContext.path(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NAMESPACE, OPENDJ_UIDNUMBER_ATTRIBUTE_NAME))); - //PrismAsserts.assertPropertyValue(uidNumberRepoAttr, USER_RANGER_UID_NUMBER); + //PrismAsserts.assertPropertyValue(uidNumberRepoAttr, USER_RANGER_UID_NUMBER); PrismProperty uidRepoAttr = repoShadow.findProperty( ItemPath.create(ShadowType.F_ATTRIBUTES, new QName(RESOURCE_OPENDJ_NAMESPACE, OPENDJ_UID_ATTRIBUTE_NAME))); - PrismAsserts.assertPropertyValue(uidRepoAttr, USER_RANGER_USERNAME); + PrismAsserts.assertPropertyValue(uidRepoAttr, USER_RANGER_USERNAME); } @Test public void test255AssignUserRangerSeals() throws Exception { - final String TEST_NAME = "test255AssignUserRangerSeals"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1377,7 +1294,7 @@ public void test255AssignUserRangerSeals() throws Exception { String accountLArgoDn = assertPosixAccount(shadow, USER_RANGER_UID_NUMBER); Entry groupSeals = openDJController.fetchEntry(groupSealsDn); //openDJController.assertAttribute(groupSeals, "memberUid", Integer.toString(USER_RANGER_UID_NUMBER)); - openDJController.assertAttribute(groupSeals, "memberUid", USER_RANGER_USERNAME); + OpenDJController.assertAttribute(groupSeals, "memberUid", USER_RANGER_USERNAME); assertGroupAssociation(shadow, groupRangersOid); assertGroupAssociation(shadow, groupSealsOid); @@ -1385,7 +1302,6 @@ public void test255AssignUserRangerSeals() throws Exception { @Test public void test256UnAssignUserRangerSealsKeepRangers() throws Exception { - final String TEST_NAME = "test256UnAssignUserRangerSealsKeepRangers"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1413,17 +1329,16 @@ public void test256UnAssignUserRangerSealsKeepRangers() throws Exception { // account should still be in the rangers group Entry groupRangers = openDJController.fetchEntry(groupRangersDn); //openDJController.assertAttribute(groupRangers, "memberUid", Integer.toString(USER_RANGER_UID_NUMBER)); - openDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME); + OpenDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME); // account should not be in the group anymore. memberUid should be // empty... Entry groupSeals = openDJController.fetchEntry(groupSealsDn); - openDJController.assertNoAttribute(groupSeals, "memberUid"); + OpenDJController.assertNoAttribute(groupSeals, "memberUid"); } @Test public void test257RenameUserAndAccountsCheckGroupmembership() throws Exception { - final String TEST_NAME = "test257RenameUserAndAccountsCheckGroupmembership"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1455,14 +1370,12 @@ public void test257RenameUserAndAccountsCheckGroupmembership() throws Exception Entry groupRangers = openDJController.fetchEntry(groupRangersDn); assertUnixGroup(shadowGroup, ROLE_RANGERS_GID); - openDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME_RENAMED); + OpenDJController.assertAttribute(groupRangers, "memberUid", USER_RANGER_USERNAME_RENAMED); } - @Test public void test260DeleteUserUsrangerUnix() throws Exception { - final String TEST_NAME = "test260DeleteUserUsrangerUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1490,7 +1403,6 @@ public void test260DeleteUserUsrangerUnix() throws Exception { */ @Test public void test270RenameUnixGroupSeals() throws Exception { - final String TEST_NAME = "test270RenameUnixGroupSeals"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1512,13 +1424,11 @@ public void test270RenameUnixGroupSeals() throws Exception { display("Shadow (model)", shadow); PrismObject shadowRepo = repositoryService.getObject(ShadowType.class, groupSealsOid, null, result); display("Shadow (repo)", shadowRepo); - String newGroupSealsDn = assertUnixGroup(shadow, ROLE_SEALS_GID); - + assertUnixGroup(shadow, ROLE_SEALS_GID); } @Test public void test300AddUserCapsizeUnixFail() throws Exception { - final String TEST_NAME = "test300AddUserCapsizeUnixFail"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1562,7 +1472,6 @@ public void test300AddUserCapsizeUnixFail() throws Exception { */ @Test public void test310AddUserWallyUnix() throws Exception { - final String TEST_NAME = "test310AddUserWallyUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1602,23 +1511,22 @@ public void test310AddUserWallyUnix() throws Exception { */ @Test public void test312AccountWallyRemovePosixObjectclassNative() throws Exception { - final String TEST_NAME = "test312AccountWallyRemovePosixObjectclassNative"; Task task = getTestTask(); OperationResult result = task.getResult(); - openDJController.executeLdifChange("dn: "+accountWallyDn+"\n"+ - "changetype: modify\n"+ - "delete: objectclass\n"+ - "objectclass: posixAccount\n"+ - "-\n"+ - "delete: uidNumber\n"+ - "uidNumber: "+USER_WALLY_UID_NUMBER+"\n"+ - "-\n"+ - "delete: gidNumber\n"+ - "gidNumber: "+USER_WALLY_UID_NUMBER+"\n"+ - "-\n"+ - "delete: homeDirectory\n"+ - "homeDirectory: /home/wally"); + openDJController.executeLdifChange("dn: " + accountWallyDn + "\n" + + "changetype: modify\n" + + "delete: objectclass\n" + + "objectclass: posixAccount\n" + + "-\n" + + "delete: uidNumber\n" + + "uidNumber: " + USER_WALLY_UID_NUMBER + "\n" + + "-\n" + + "delete: gidNumber\n" + + "gidNumber: " + USER_WALLY_UID_NUMBER + "\n" + + "-\n" + + "delete: homeDirectory\n" + + "homeDirectory: /home/wally"); Entry entryWallyBefore = openDJController.fetchEntry(accountWallyDn); display("Wally LDAP account before", entryWallyBefore); @@ -1652,23 +1560,22 @@ public void test312AccountWallyRemovePosixObjectclassNative() throws Exception { */ @Test public void test314AccountWallyAddPosixObjectclassNative() throws Exception { - final String TEST_NAME = "test314AccountWallyAddPosixObjectclassNative"; Task task = getTestTask(); OperationResult result = task.getResult(); - openDJController.executeLdifChange("dn: "+accountWallyDn+"\n"+ - "changetype: modify\n"+ - "add: objectclass\n"+ - "objectclass: posixAccount\n"+ - "-\n"+ - "add: uidNumber\n"+ - "uidNumber: "+USER_WALLY_UID_NUMBER+"\n"+ - "-\n"+ - "add: gidNumber\n"+ - "gidNumber: "+USER_WALLY_UID_NUMBER+"\n"+ - "-\n"+ - "add: homeDirectory\n"+ - "homeDirectory: /home/wally"); + openDJController.executeLdifChange("dn: " + accountWallyDn + "\n" + + "changetype: modify\n" + + "add: objectclass\n" + + "objectclass: posixAccount\n" + + "-\n" + + "add: uidNumber\n" + + "uidNumber: " + USER_WALLY_UID_NUMBER + "\n" + + "-\n" + + "add: gidNumber\n" + + "gidNumber: " + USER_WALLY_UID_NUMBER + "\n" + + "-\n" + + "add: homeDirectory\n" + + "homeDirectory: /home/wally"); Entry entryWallyBefore = openDJController.fetchEntry(accountWallyDn); display("Wally LDAP account before", entryWallyBefore); @@ -1698,7 +1605,6 @@ public void test314AccountWallyAddPosixObjectclassNative() throws Exception { @Test public void test400ListAllAccountsObjectClass() throws Exception { - final String TEST_NAME = "test400ListAllAccountsObjectClass"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1720,7 +1626,6 @@ public void test400ListAllAccountsObjectClass() throws Exception { @Test public void test401ListAllAccountsKindIntent() throws Exception { - final String TEST_NAME = "test401ListAllAccountsKindIntent"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1743,7 +1648,6 @@ public void test401ListAllAccountsKindIntent() throws Exception { @Test public void test402ListLdapGroupsKindIntent() throws Exception { - final String TEST_NAME = "test402ListLdapGroupsKindIntent"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1766,7 +1670,6 @@ public void test402ListLdapGroupsKindIntent() throws Exception { @Test public void test403ListUnixGroupsKindIntent() throws Exception { - final String TEST_NAME = "test403ListUnixGroupsKindIntent"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1788,7 +1691,6 @@ public void test403ListUnixGroupsKindIntent() throws Exception { @Test public void test500AddUserStan() throws Exception { - final String TEST_NAME = "test500AddUserStan"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1821,7 +1723,6 @@ public void test500AddUserStan() throws Exception { @Test public void test510StanDisablePosixAssocAndReconcile() throws Exception { - final String TEST_NAME = "test510StanDisablePosixAssocAndReconcile"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -1918,46 +1819,49 @@ protected void assertUserPosix(PrismObject user, String username, Stri assertUser(user, user.getOid(), username, firstName + " " + lastName, firstName, lastName); PrismContainer extension = user.getExtension(); - assertNotNull("No extension in "+user, extension); + assertNotNull("No extension in " + user, extension); PrismAsserts.assertPropertyValue(extension, EXTENSION_UID_NUMBER_NAME, Integer.toString(uidNumber)); } protected String assertBasicAccount(PrismObject shadow) throws DirectoryException { ShadowType shadowType = shadow.asObjectable(); - assertEquals("Wrong objectclass in "+shadow, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); - assertTrue("Unexpected auxiliary objectclasses in "+shadow + ": "+shadowType.getAuxiliaryObjectClass(), + assertEquals("Wrong objectclass in " + shadow, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); + assertTrue("Unexpected auxiliary objectclasses in " + shadow + ": " + shadowType.getAuxiliaryObjectClass(), shadowType.getAuxiliaryObjectClass().isEmpty()); + //noinspection ConstantConditions String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); Entry entry = openDJController.fetchEntry(dn); - assertNotNull("No ou LDAP entry for "+dn); + assertNotNull("No ou LDAP entry for " + dn, entry); display("Posix account entry", entry); - openDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); - openDJController.assertNoObjectClass(entry, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertNoObjectClass(entry, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); return entry.getDN().toString(); } protected String assertAccount(PrismObject shadow, QName... expectedAuxObjectClasses) throws DirectoryException { ShadowType shadowType = shadow.asObjectable(); - assertEquals("Wrong objectclass in "+shadow, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); - PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in "+shadow, + assertEquals("Wrong objectclass in " + shadow, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); + PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in " + shadow, shadowType.getAuxiliaryObjectClass(), expectedAuxObjectClasses); + //noinspection ConstantConditions String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); Entry entry = openDJController.fetchEntry(dn); - assertNotNull("No ou LDAP entry for "+dn); + assertNotNull("No ou LDAP entry for " + dn, entry); display("Posix account entry", entry); - openDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); return entry.getDN().toString(); } protected String assertPosixAccount(PrismObject shadow, Integer expectedUid) throws DirectoryException { ShadowType shadowType = shadow.asObjectable(); - assertEquals("Wrong objectclass in "+shadow, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); - PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in "+shadow, + assertEquals("Wrong objectclass in " + shadow, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); + PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in " + shadow, shadowType.getAuxiliaryObjectClass(), OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME); + //noinspection ConstantConditions String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); if (expectedUid != null) { ResourceAttribute uidNumberAttr = ShadowUtil @@ -1969,13 +1873,13 @@ protected String assertPosixAccount(PrismObject shadow, Integer expe } Entry entry = openDJController.fetchEntry(dn); - assertNotNull("No ou LDAP entry for "+dn); + assertNotNull("No ou LDAP entry for " + dn, entry); display("Posix account entry", entry); - openDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); - openDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertObjectClass(entry, OPENDJ_ACCOUNT_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); if (expectedUid != null) { - openDJController.assertAttribute(entry, OPENDJ_UIDNUMBER_ATTRIBUTE_NAME, Integer.toString(expectedUid)); - openDJController.assertAttribute(entry, OPENDJ_GIDNUMBER_ATTRIBUTE_NAME, Integer.toString(expectedUid)); + OpenDJController.assertAttribute(entry, OPENDJ_UIDNUMBER_ATTRIBUTE_NAME, Integer.toString(expectedUid)); + OpenDJController.assertAttribute(entry, OPENDJ_GIDNUMBER_ATTRIBUTE_NAME, Integer.toString(expectedUid)); } return entry.getDN().toString(); @@ -1986,21 +1890,21 @@ protected ShadowAssociationType assertGroupAssociation(PrismObject a if (association != null) { return association; } - AssertJUnit.fail("No association for "+groupShadowOid+" in "+accountShadow); + AssertJUnit.fail("No association for " + groupShadowOid + " in " + accountShadow); return null; // NOT REACHED } protected void assertNoGroupAssociation(PrismObject accountShadow, String groupShadowOid) { ShadowAssociationType association = findAssociation(accountShadow, groupShadowOid); - assertNull("Unexpected association for "+groupShadowOid+" in "+accountShadow, association); + assertNull("Unexpected association for " + groupShadowOid + " in " + accountShadow, association); } @Nullable private ShadowAssociationType findAssociation(PrismObject accountShadow, String groupShadowOid) { ShadowType accountShadowType = accountShadow.asObjectable(); - for (ShadowAssociationType association: accountShadowType.getAssociation()) { - assertNotNull("Association without shadowRef in "+accountShadow+": "+association, association.getShadowRef()); - assertNotNull("Association without shadowRef OID in "+accountShadow+": "+association, association.getShadowRef().getOid()); + for (ShadowAssociationType association : accountShadowType.getAssociation()) { + assertNotNull("Association without shadowRef in " + accountShadow + ": " + association, association.getShadowRef()); + assertNotNull("Association without shadowRef OID in " + accountShadow + ": " + association, association.getShadowRef().getOid()); if (association.getShadowRef().getOid().equals(groupShadowOid)) { return association; } @@ -2038,42 +1942,44 @@ private PrismObject createUnixGroupRole(String name, String metaRoleOi private String assertLdapGroup(PrismObject shadow) throws DirectoryException { ShadowType shadowType = shadow.asObjectable(); - assertEquals("Wrong objectclass in "+shadow, OPENDJ_GROUP_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); - assertTrue("Unexpected auxiliary objectclasses in "+shadow + ": "+shadowType.getAuxiliaryObjectClass(), + assertEquals("Wrong objectclass in " + shadow, OPENDJ_GROUP_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); + assertTrue("Unexpected auxiliary objectclasses in " + shadow + ": " + shadowType.getAuxiliaryObjectClass(), shadowType.getAuxiliaryObjectClass().isEmpty()); + //noinspection ConstantConditions String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); Entry entry = openDJController.fetchEntry(dn); - assertNotNull("No group LDAP entry for "+dn); + assertNotNull("No group LDAP entry for " + dn, entry); display("Ldap group entry", entry); - openDJController.assertObjectClass(entry, OPENDJ_GROUP_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); - openDJController.assertNoObjectClass(entry, OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertObjectClass(entry, OPENDJ_GROUP_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertNoObjectClass(entry, OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); return entry.getDN().toString(); } private String assertUnixGroup(PrismObject shadow, Integer expectedGidNumber) throws DirectoryException { ShadowType shadowType = shadow.asObjectable(); - assertEquals("Wrong objectclass in "+shadow, OPENDJ_GROUP_UNIX_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); - PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in "+shadow, + assertEquals("Wrong objectclass in " + shadow, OPENDJ_GROUP_UNIX_STRUCTURAL_OBJECTCLASS_NAME, shadowType.getObjectClass()); + PrismAsserts.assertEqualsCollectionUnordered("Wrong auxiliary objectclasses in " + shadow, shadowType.getAuxiliaryObjectClass(), OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME); + //noinspection ConstantConditions String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); ResourceAttribute gidNumberAttr = ShadowUtil.getAttribute(shadow, new QName(RESOURCE_OPENDJ_NAMESPACE, OPENDJ_GIDNUMBER_ATTRIBUTE_NAME)); PrismAsserts.assertPropertyValue(gidNumberAttr, expectedGidNumber); Entry entry = openDJController.fetchEntry(dn); - assertNotNull("No group LDAP entry for "+dn); + assertNotNull("No group LDAP entry for " + dn, entry); display("Posix account entry", entry); - openDJController.assertObjectClass(entry, OPENDJ_GROUP_UNIX_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); - openDJController.assertObjectClass(entry, OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); - openDJController.assertAttribute(entry, "gidNumber", expectedGidNumber.toString()); + OpenDJController.assertObjectClass(entry, OPENDJ_GROUP_UNIX_STRUCTURAL_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertObjectClass(entry, OPENDJ_GROUP_POSIX_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()); + OpenDJController.assertAttribute(entry, "gidNumber", expectedGidNumber.toString()); return entry.getDN().toString(); } protected void assertModifyTimestamp(PrismObject shadow, long startTs, long endTs) throws Exception { Long actual = getTimestampAttribute(shadow); - TestUtil.assertBetween("Wrong modify timestamp attribute in "+shadow, startTs-1000, endTs+1000, actual); + TestUtil.assertBetween("Wrong modify timestamp attribute in " + shadow, startTs - 1000, endTs + 1000, actual); } protected Long getTimestampAttribute(PrismObject shadow) throws Exception { diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnixTolerantAux.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnixTolerantAux.java index 97170f9dcd2..db4e003d329 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnixTolerantAux.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestUnixTolerantAux.java @@ -6,19 +6,12 @@ */ package com.evolveum.midpoint.testing.story; -import static org.testng.AssertJUnit.assertFalse; -import static org.testng.AssertJUnit.assertEquals; import static org.testng.AssertJUnit.assertNotNull; -import static org.testng.AssertJUnit.assertNull; -import static org.testng.AssertJUnit.assertTrue; import java.io.File; import java.util.Arrays; - import javax.xml.namespace.QName; -import com.evolveum.midpoint.xml.ns._public.common.common_3.*; - import org.apache.directory.api.util.GeneralizedTime; import org.opends.server.types.DirectoryException; import org.opends.server.types.Entry; @@ -35,15 +28,18 @@ import com.evolveum.midpoint.schema.result.OperationResult; import com.evolveum.midpoint.schema.util.ShadowUtil; import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.ldap.OpenDJController; +import com.evolveum.midpoint.xml.ns._public.common.common_3.ShadowType; +import com.evolveum.midpoint.xml.ns._public.common.common_3.UserType; /** * Unix test with tolerant auxiliary object classes. - * + *

* Also this is using different timestamp format in LDAP connector configuration. * * @author Radovan Semancik */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) @Listeners({ com.evolveum.midpoint.tools.testng.AlphabeticalMethodInterceptor.class }) public class TestUnixTolerantAux extends TestUnix { @@ -111,7 +107,6 @@ protected void assertTest137Account(PrismObject shadow) throws Excep @Test public void test140AssignUserLargoBasic() throws Exception { - final String TEST_NAME = "test140AssignUserLargoBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -144,20 +139,19 @@ public void test140AssignUserLargoBasic() throws Exception { */ @Test public void test142MeddleWithAccountAndReconcileUserLargo() throws Exception { - final String TEST_NAME = "test142MeddleWithAccountAndReconcileUserLargo"; Task task = getTestTask(); OperationResult result = task.getResult(); PrismObject userBefore = findUserByUsername(USER_LARGO_USERNAME); openDJController.executeLdifChange( - "dn: "+accountLargoDn+"\n"+ - "changetype: modify\n" + - "add: objectClass\n" + - "objectClass: "+OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME.getLocalPart()+"\n" + - "-\n" + - "add: labeledURI\n" + - "labeledURI: "+ URI_WHATEVER + "\n" + "dn: " + accountLargoDn + "\n" + + "changetype: modify\n" + + "add: objectClass\n" + + "objectClass: " + OPENDJ_ACCOUNT_LABELED_URI_OBJECT_AUXILIARY_OBJECTCLASS_NAME.getLocalPart() + "\n" + + "-\n" + + "add: labeledURI\n" + + "labeledURI: " + URI_WHATEVER + "\n" ); Entry entryBefore = openDJController.fetchEntry(accountLargoDn); @@ -191,7 +185,6 @@ public void test142MeddleWithAccountAndReconcileUserLargo() throws Exception { @Test public void test144AssignUserLargoUnix() throws Exception { - final String TEST_NAME = "test144AssignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -221,7 +214,6 @@ public void test144AssignUserLargoUnix() throws Exception { @Test public void test146UnassignUserLargoUnix() throws Exception { - final String TEST_NAME = "test146UnassignUserLargoUnix"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -251,7 +243,6 @@ public void test146UnassignUserLargoUnix() throws Exception { @Test public void test149UnAssignUserLargoBasic() throws Exception { - final String TEST_NAME = "test149UnAssignUserLargoBasic"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -291,7 +282,7 @@ protected Long getTimestampAttribute(PrismObject shadow) throws Exce return null; } if (!attributeValue.endsWith("Z")) { - fail("Non-zulu timestamp: "+attributeValue); + fail("Non-zulu timestamp: " + attributeValue); } GeneralizedTime gt = new GeneralizedTime(attributeValue); return gt.getCalendar().getTimeInMillis(); @@ -303,12 +294,12 @@ private void assertUserAuxes(PrismObject userAfter, QName... expectedA } private void assertLabeledUri(PrismObject shadow, String expecteduri) throws DirectoryException { - ShadowType shadowType = shadow.asObjectable(); + //noinspection ConstantConditions String dn = (String) ShadowUtil.getSecondaryIdentifiers(shadow).iterator().next().getRealValue(); Entry entry = openDJController.fetchEntry(dn); - assertNotNull("No ou LDAP entry for "+dn); + assertNotNull("No ou LDAP entry for " + dn, entry); display("Posix account entry", entry); - openDJController.assertAttribute(entry, OPENDJ_LABELED_URI_ATTRIBUTE_NAME, expecteduri); + OpenDJController.assertAttribute(entry, OPENDJ_LABELED_URI_ATTRIBUTE_NAME, expecteduri); } } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java index 9f3aecbf747..ea94d16471b 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/TestVillage.java @@ -6,6 +6,20 @@ * and European Union Public License. See LICENSE file for details. */ +import static org.testng.AssertJUnit.*; + +import java.io.File; +import java.util.List; +import javax.xml.namespace.QName; + +import org.opends.server.types.DirectoryException; +import org.opends.server.types.Entry; +import org.springframework.test.annotation.DirtiesContext; +import org.springframework.test.annotation.DirtiesContext.ClassMode; +import org.springframework.test.context.ContextConfiguration; +import org.testng.annotations.AfterClass; +import org.testng.annotations.Test; + import com.evolveum.icf.dummy.resource.DummyAccount; import com.evolveum.icf.dummy.resource.DummyObjectClass; import com.evolveum.icf.dummy.resource.DummyResource; @@ -35,25 +49,11 @@ import com.evolveum.midpoint.util.MiscUtil; import com.evolveum.midpoint.util.exception.*; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -import org.opends.server.types.DirectoryException; -import org.opends.server.types.Entry; -import org.springframework.test.annotation.DirtiesContext; -import org.springframework.test.annotation.DirtiesContext.ClassMode; -import org.springframework.test.context.ContextConfiguration; -import org.testng.annotations.AfterClass; -import org.testng.annotations.Test; - -import javax.xml.namespace.QName; -import java.io.File; -import java.util.List; - -import static org.testng.AssertJUnit.*; /** * @author Radovan Semancik - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) public class TestVillage extends AbstractStoryTest { @@ -122,14 +122,14 @@ public class TestVillage extends AbstractStoryTest { private static final String ACCOUNT_HERMAN_LAST_NAME = "Toothrot"; private static final String ACCOUNT_HERMAN_LOC = "Monkey Island"; private static final String ACCOUNT_HERMAN_ORG = "Gov"; - private static final String USER_HERMAN_NAME = "G."+ACCOUNT_HERMAN_FIST_NAME+"."+ACCOUNT_HERMAN_LAST_NAME; + private static final String USER_HERMAN_NAME = "G." + ACCOUNT_HERMAN_FIST_NAME + "." + ACCOUNT_HERMAN_LAST_NAME; private static final String ACCOUNT_LEMONHEAD_USERNAME = "lemonhead"; private static final String ACCOUNT_LEMONHEAD_FIST_NAME = "Lemonhead"; private static final String ACCOUNT_LEMONHEAD_LAST_NAME = "Canibal"; private static final String ACCOUNT_LEMONHEAD_LOC = "Monkey Island"; private static final String ACCOUNT_LEMONHEAD_ORG = "Exec"; - private static final String USER_LEMONHEAD_NAME = "E."+ACCOUNT_LEMONHEAD_FIST_NAME+"."+ACCOUNT_LEMONHEAD_LAST_NAME; + private static final String USER_LEMONHEAD_NAME = "E." + ACCOUNT_LEMONHEAD_FIST_NAME + "." + ACCOUNT_LEMONHEAD_LAST_NAME; private static final String ACCOUNT_SHARPTOOTH_USERNAME = "sharptooth"; private static final String ACCOUNT_SHARPTOOTH_FIST_NAME = "Sharptooth"; @@ -144,7 +144,7 @@ public class TestVillage extends AbstractStoryTest { private static final String ACCOUNT_MANCOMB_LAST_NAME = "Seepgood"; private static final String ACCOUNT_MANCOMB_LOC = "-"; private static final String ACCOUNT_MANCOMB_ORG = "-"; - private static final String USER_MANCOMB_NAME = ACCOUNT_MANCOMB_FIST_NAME+"."+ACCOUNT_MANCOMB_LAST_NAME; + private static final String USER_MANCOMB_NAME = ACCOUNT_MANCOMB_FIST_NAME + "." + ACCOUNT_MANCOMB_LAST_NAME; private static final String ACCOUNT_COBB_USERNAME = "cobb"; private static final String ACCOUNT_COBB_FIST_NAME = "Cobb"; @@ -165,7 +165,7 @@ public class TestVillage extends AbstractStoryTest { private static final String ACCOUNT_WALLY_USERNAME = "wally"; private static final String ACCOUNT_WALLY_FIST_NAME = "Wally"; private static final String ACCOUNT_WALLY_LAST_NAME = "Feed"; - private static final String USER_WALLY_NAME = ACCOUNT_WALLY_FIST_NAME+"."+ACCOUNT_WALLY_LAST_NAME; + private static final String USER_WALLY_NAME = ACCOUNT_WALLY_FIST_NAME + "." + ACCOUNT_WALLY_LAST_NAME; private static final String ACCOUNT_AUGUSTUS_USERNAME = "augustus"; private static final String ACCOUNT_AUGUSTUS_FIST_NAME = "Augustus"; @@ -191,7 +191,6 @@ public class TestVillage extends AbstractStoryTest { private static final String GROUP_PROJECT_JOLLY_ROGER_ADMIN_DN = "cn=admins,ou=Jolly Roger,dc=example,dc=com"; - protected static DummyResource dummyResourceSrc; protected static DummyResourceContoller dummyResourceCtlSrc; protected ResourceType resourceDummySrcType; @@ -263,8 +262,7 @@ protected File getSystemConfigurationFile() { @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultHr = modelService.testResource(RESOURCE_DUMMY_SOURCE_OID, task); TestUtil.assertSuccess(testResultHr); @@ -286,8 +284,7 @@ public void test000Sanity() throws Exception { */ @Test public void test020ResourceOpenDjGet() throws Exception { - final String TEST_NAME = "test020ResourceOpenDjGet"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult result = task.getResult(); rememberCounter(InternalCounters.RESOURCE_SCHEMA_FETCH_COUNT); @@ -356,8 +353,8 @@ public void test022ResourceOpenDjRefinedSchema() throws Exception { RefinedResourceSchema refinedSchemaAfter = RefinedResourceSchema.getRefinedSchema(resourceAfter); long t4 = System.currentTimeMillis(); - display("Times", "getObject(RESOURCE_OPENDJ_OID): "+(t1-t0)+"ms\ngetResourceSchema: "+(t3-t2) - +"ms\ngetRefinedSchema: "+(t4-t3)+"ms"); + display("Times", "getObject(RESOURCE_OPENDJ_OID): " + (t1 - t0) + "ms\ngetResourceSchema: " + (t3 - t2) + + "ms\ngetRefinedSchema: " + (t4 - t3) + "ms"); // variable number of clones: 1 or 2 because of trigger scanner task assertCounterIncrement(InternalCounters.PRISM_OBJECT_CLONE_COUNT, 1, 2); @@ -369,15 +366,12 @@ public void test022ResourceOpenDjRefinedSchema() throws Exception { assertCounterIncrement(InternalCounters.CONNECTOR_INSTANCE_CONFIGURATION_COUNT, 0); assertCounterIncrement(InternalCounters.CONNECTOR_SCHEMA_PARSE_COUNT, 0); - assertTrue("Resource schema has changed", resourceSchemaBefore == resourceSchemaAfter ); - assertTrue("Refined schema has changed", refinedSchemaBefore == refinedSchemaAfter ); + assertSame("Resource schema has changed", resourceSchemaBefore, resourceSchemaAfter); + assertSame("Refined schema has changed", refinedSchemaBefore, refinedSchemaAfter); } @Test public void test100AddSrcAccountHerman() throws Exception { - final String TEST_NAME = "test100AddSrcAccountHerman"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_HERMAN_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_HERMAN_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_HERMAN_LAST_NAME); @@ -396,9 +390,6 @@ public void test100AddSrcAccountHerman() throws Exception { @Test public void test101HermanAssignBasicRole() throws Exception { - final String TEST_NAME = "test101HermanAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_HERMAN_NAME); // WHEN @@ -413,9 +404,6 @@ public void test101HermanAssignBasicRole() throws Exception { @Test public void test102HermanUnAssignBasicRole() throws Exception { - final String TEST_NAME = "test102HermanUnAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_HERMAN_NAME); // WHEN @@ -430,9 +418,6 @@ public void test102HermanUnAssignBasicRole() throws Exception { @Test public void test103HermanAssignBasicAndSimpleRole() throws Exception { - final String TEST_NAME = "test103HermanAssignBasicAndSimpleRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_HERMAN_NAME); // WHEN @@ -449,9 +434,6 @@ public void test103HermanAssignBasicAndSimpleRole() throws Exception { @Test public void test104HermanUnAssignSimpleRoleThenBasic() throws Exception { - final String TEST_NAME = "test104HermanUnAssignSimpleRoleThenBasic"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_HERMAN_NAME); // WHEN @@ -474,12 +456,8 @@ public void test104HermanUnAssignSimpleRoleThenBasic() throws Exception { assertNoLdapLocGov(userAfter, ACCOUNT_HERMAN_LOC, ACCOUNT_HERMAN_ORG); } - @Test public void test105ModifySrcAccountHermanRemoveLoc() throws Exception { - final String TEST_NAME = "test105ModifySrcAccountHermanRemoveLoc"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); // WHEN @@ -494,9 +472,6 @@ public void test105ModifySrcAccountHermanRemoveLoc() throws Exception { @Test public void test106HermanAssignBasicRole() throws Exception { - final String TEST_NAME = "test106HermanAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_HERMAN_NAME); // WHEN @@ -511,9 +486,6 @@ public void test106HermanAssignBasicRole() throws Exception { @Test public void test107ModifySrcAccountHermanAddLoc() throws Exception { - final String TEST_NAME = "test107ModifySrcAccountHermanAddLoc"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); // WHEN @@ -529,9 +501,6 @@ public void test107ModifySrcAccountHermanAddLoc() throws Exception { @Test public void test108ModifySrcAccountHermanRemoveLoc() throws Exception { - final String TEST_NAME = "test108ModifySrcAccountHermanRemoveLoc"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); // WHEN @@ -547,9 +516,6 @@ public void test108ModifySrcAccountHermanRemoveLoc() throws Exception { @Test public void test109HermanUnAssignBasicRole() throws Exception { - final String TEST_NAME = "test109HermanUnAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_HERMAN_NAME); // WHEN @@ -564,9 +530,6 @@ public void test109HermanUnAssignBasicRole() throws Exception { @Test public void test110AddSrcAccountLemonhead() throws Exception { - final String TEST_NAME = "test110AddSrcAccountLemonhead"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_LEMONHEAD_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_LEMONHEAD_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_LEMONHEAD_LAST_NAME); @@ -590,9 +553,6 @@ public void test110AddSrcAccountLemonhead() throws Exception { */ @Test public void test120AddSrcAccountWally() throws Exception { - final String TEST_NAME = "test120AddSrcAccountWally"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_WALLY_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_WALLY_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_WALLY_LAST_NAME); @@ -609,9 +569,6 @@ public void test120AddSrcAccountWally() throws Exception { @Test public void test121WallyAssignBasicRole() throws Exception { - final String TEST_NAME = "test121WallyAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_WALLY_NAME); // WHEN @@ -625,9 +582,6 @@ public void test121WallyAssignBasicRole() throws Exception { @Test public void test122WallyUnAssignBasicRole() throws Exception { - final String TEST_NAME = "test122WallyUnAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_WALLY_NAME); // WHEN @@ -644,9 +598,6 @@ public void test122WallyUnAssignBasicRole() throws Exception { */ @Test public void test130AddSrcAccountMancomb() throws Exception { - final String TEST_NAME = "test130AddSrcAccountMancomb"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount newAccount = new DummyAccount(ACCOUNT_MANCOMB_USERNAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_FIRST_NAME, ACCOUNT_MANCOMB_FIST_NAME); newAccount.addAttributeValue(DUMMY_ACCOUNT_ATTRIBUTE_SRC_LAST_NAME, ACCOUNT_MANCOMB_LAST_NAME); @@ -665,9 +616,6 @@ public void test130AddSrcAccountMancomb() throws Exception { @Test public void test131MancombAssignBasicRole() throws Exception { - final String TEST_NAME = "test131WallyAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_MANCOMB_NAME); // WHEN @@ -681,9 +629,6 @@ public void test131MancombAssignBasicRole() throws Exception { @Test public void test132MancombUnAssignBasicRole() throws Exception { - final String TEST_NAME = "test132MancombUnAssignBasicRole"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - PrismObject user = findUserByUsername(USER_MANCOMB_NAME); // WHEN @@ -695,15 +640,11 @@ public void test132MancombUnAssignBasicRole() throws Exception { assertLocGov(userAfter, ACCOUNT_MANCOMB_LOC, ACCOUNT_MANCOMB_ORG); } - /** * Change of org should trigger rename */ @Test public void test150ModifySrcAccountHermanReplaceOrg() throws Exception { - final String TEST_NAME = "test150ModifySrcAccountHermanReplaceOrg"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); // WHEN @@ -724,9 +665,6 @@ public void test150ModifySrcAccountHermanReplaceOrg() throws Exception { */ @Test public void test152ModifySrcAccountHermanDeleteOrg() throws Exception { - final String TEST_NAME = "test152ModifySrcAccountHermanDeleteOrg"; - Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); - DummyAccount account = dummyResourceSrc.getAccountByUsername(ACCOUNT_HERMAN_USERNAME); // WHEN @@ -748,7 +686,6 @@ public void test152ModifySrcAccountHermanDeleteOrg() throws Exception { @Test public void test200CreateUserAssignOrgPwdPolicy() throws Exception { - final String TEST_NAME = "test200CreateUserAssignOrgPwdPolicy"; Task task = getTestTask(); OperationResult result = createOperationResult(); @@ -783,22 +720,19 @@ public void test200CreateUserAssignOrgPwdPolicy() throws Exception { //TODO: assert added user PrismObject userMikeAfter = getUser(USER_MIKE_OID); - UserAsserter.forUser(userMikeAfter). - assertAssignments(2). - assertLinks(0); + UserAsserter.forUser(userMikeAfter). + assertAssignments(2). + assertLinks(0); } @Test - public void test201unassignRole() throws Exception{ - final String TEST_NAME = "test201unassignRole"; + public void test201unassignRole() throws Exception { unassignRole(USER_MIKE_OID, ROLE_BASIC_OID); //TODO: assertions } @Test - public void test202assignRoleOrgPwdPolicy() throws Exception{ - final String TEST_NAME = "test202assignRoleOrgPwdPolicy"; - + public void test202assignRoleOrgPwdPolicy() throws Exception { //this will throw exception, if incorrect pwd policy is selected...but some assertion will be nice :) Task task = getTestTask(); OperationResult result = task.getResult(); @@ -810,7 +744,6 @@ public void test202assignRoleOrgPwdPolicy() throws Exception{ @Test public void test300AddProjectJollyRoger() throws Exception { - final String TEST_NAME = "test300AddProjectJollyRoger"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -828,7 +761,7 @@ public void test300AddProjectJollyRoger() throws Exception { Entry ouEntry = openDJController.fetchAndAssertEntry("ou=Jolly Roger,dc=example,dc=com", "organizationalUnit"); Entry groupEntry = openDJController.fetchAndAssertEntry(GROUP_PROJECT_JOLLY_ROGER_ADMIN_DN, GROUP_OF_UNIQUE_NAMES_OBJECTCLASS_NAME); - //TODO: more assertions + //TODO: more assertions } /** @@ -840,10 +773,10 @@ public void test310ProjectJollyRogerNestedGroup() throws Exception { Task task = taskManager.createTaskInstance(TestVillage.class.getName() + "." + TEST_NAME); OperationResult result = task.getResult(); - openDJController.addEntry("dn: "+GROUP_JOLLYROGERS_DN+"\n"+ - "objectclass: "+GROUP_OF_UNIQUE_NAMES_OBJECTCLASS_NAME+"\n"+ - "cn: jollyrogers\n"+ - GROUP_MEMBER_ATTRIBUTE_NAME+": "+GROUP_PROJECT_JOLLY_ROGER_ADMIN_DN+"\n"); + openDJController.addEntry("dn: " + GROUP_JOLLYROGERS_DN + "\n" + + "objectclass: " + GROUP_OF_UNIQUE_NAMES_OBJECTCLASS_NAME + "\n" + + "cn: jollyrogers\n" + + GROUP_MEMBER_ATTRIBUTE_NAME + ": " + GROUP_PROJECT_JOLLY_ROGER_ADMIN_DN + "\n"); display("LDAP entries", openDJController.dumpEntries()); @@ -919,44 +852,44 @@ public void test350AddRepoUserNoEmployeeNumberRecompute() throws Exception { private void assertLocGov(PrismObject user, String expLoc, String expOrg) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { UserType userType = user.asObjectable(); - PrismAsserts.assertEqualsPolyString("Wrong locality in "+user, expLoc, userType.getLocality()); + PrismAsserts.assertEqualsPolyString("Wrong locality in " + user, expLoc, userType.getLocality()); if (expOrg == null) { - assertTrue("Unexpected organization in "+user+": "+userType.getOrganization(), userType.getOrganization().isEmpty()); + assertTrue("Unexpected organization in " + user + ": " + userType.getOrganization(), userType.getOrganization().isEmpty()); } else { - PrismAsserts.assertEqualsCollectionUnordered("Wrong organization in "+user, userType.getOrganization(), - PrismTestUtil.createPolyStringType(expOrg)); + PrismAsserts.assertEqualsCollectionUnordered("Wrong organization in " + user, userType.getOrganization(), + PrismTestUtil.createPolyStringType(expOrg)); } if (expLoc == null || expOrg == null) { - assertNull("Wrong costCenter in "+user+", expected empty but was "+userType.getCostCenter(), userType.getCostCenter()); + assertNull("Wrong costCenter in " + user + ", expected empty but was " + userType.getCostCenter(), userType.getCostCenter()); } else { - assertEquals("Wrong costCenter in "+user, userType.getCostCenter(), expOrg+":"+expLoc); + assertEquals("Wrong costCenter in " + user, userType.getCostCenter(), expOrg + ":" + expLoc); } if (expOrg != null && !expOrg.equals("-")) { PrismObject org = findObjectByName(OrgType.class, expOrg); assertAssigned(user, org.getOid(), OrgType.COMPLEX_TYPE); String orgId = org.asObjectable().getIdentifier(); - PrismAsserts.assertEqualsCollectionUnordered("Wrong organizationalUnit in "+user, + PrismAsserts.assertEqualsCollectionUnordered("Wrong organizationalUnit in " + user, userType.getOrganizationalUnit(), PrismTestUtil.createPolyStringType(orgId)); - assertEquals("Wrong title in "+user, "Member of "+orgId, userType.getTitle().getOrig()); + assertEquals("Wrong title in " + user, "Member of " + orgId, userType.getTitle().getOrig()); } else { assertAssignments(user, OrgType.class, 0); - assertTrue("Unexpected organizationalUnit in "+user+": "+userType.getOrganizationalUnit(), userType.getOrganizationalUnit().isEmpty()); - assertNull("Unexpected title in "+user+": "+userType.getDescription(), userType.getTitle()); + assertTrue("Unexpected organizationalUnit in " + user + ": " + userType.getOrganizationalUnit(), userType.getOrganizationalUnit().isEmpty()); + assertNull("Unexpected title in " + user + ": " + userType.getDescription(), userType.getTitle()); } } private void assertUserNoRole(PrismObject user, String firstName, String lastName, String orgName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { String username = getUsername(firstName, lastName, orgName); - assertNotNull("No "+username+" user", user); + assertNotNull("No " + username + " user", user); display("User", user); - assertUser(user, user.getOid(), username, firstName+" "+lastName, - firstName, lastName); - assertEmployeeNumber(user); - assertLinks(user, 1); + assertUser(user, user.getOid(), username, firstName + " " + lastName, + firstName, lastName); + assertEmployeeNumber(user); + assertLinks(user, 1); assertAccount(user, RESOURCE_DUMMY_SOURCE_OID); assertAssignments(user, RoleType.class, 0); - openDJController.assertNoEntry("uid="+username+",ou=people,dc=example,dc=com"); + openDJController.assertNoEntry("uid=" + username + ",ou=people,dc=example,dc=com"); } private void assertUserLdap(PrismObject user, String firstName, String lastName, String orgName) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { @@ -965,11 +898,11 @@ private void assertUserLdap(PrismObject user, String firstName, String private void assertUserLdap(PrismObject user, String firstName, String lastName, String orgName, int assignments) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { String username = getUsername(firstName, lastName, orgName); - assertNotNull("No "+username+" user", user); + assertNotNull("No " + username + " user", user); display("User", user); - assertUser(user, user.getOid(), username, firstName+" "+lastName, - firstName, lastName); - assertEmployeeNumber(user); + assertUser(user, user.getOid(), username, firstName + " " + lastName, + firstName, lastName); + assertEmployeeNumber(user); assertLinks(user, 2); assertAccount(user, RESOURCE_DUMMY_SOURCE_OID); @@ -979,29 +912,27 @@ private void assertUserLdap(PrismObject user, String firstName, String assertAccount(user, RESOURCE_OPENDJ_OID); PrismReferenceValue linkRef = getLinkRef(user, RESOURCE_OPENDJ_OID); PrismObject shadow = getShadowModel(linkRef.getOid()); - display("OpenDJ shadow linked to "+user, shadow); - IntegrationTestTools.assertSecondaryIdentifier(shadow, "uid="+username+",ou=people,dc=example,dc=com"); + display("OpenDJ shadow linked to " + user, shadow); + IntegrationTestTools.assertSecondaryIdentifier(shadow, "uid=" + username + ",ou=people,dc=example,dc=com"); } private void assertEmployeeNumber(PrismObject user) { String employeeNumber = user.asObjectable().getEmployeeNumber(); - assertEquals("Wrong employeeNumber in "+user, user.getOid(), employeeNumber); + assertEquals("Wrong employeeNumber in " + user, user.getOid(), employeeNumber); } private String getUsername(String firstName, String lastName, String orgName) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, ExpressionEvaluationException { - String username = firstName+"."+lastName; + String username = firstName + "." + lastName; if (orgName != null) { PrismObject org = findObjectByName(OrgType.class, orgName); - username = org.asObjectable().getIdentifier()+"."+username; + username = org.asObjectable().getIdentifier() + "." + username; } return username; } private void assertLdapLocGov(PrismObject user, String expLoc, String expOrg) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { - UserType userType = user.asObjectable(); - - String groupCn = expOrg+":"+expLoc; - String groupDn = "cn="+groupCn+",ou=groups,"+openDJController.getSuffix(); + String groupCn = expOrg + ":" + expLoc; + String groupDn = "cn=" + groupCn + ",ou=groups," + openDJController.getSuffix(); Entry groupEntry = openDJController.fetchAndAssertEntry(groupDn, "groupOfUniqueNames"); display("Group entry", groupEntry); @@ -1011,15 +942,15 @@ private void assertLdapLocGov(PrismObject user, String expLoc, String openDJController.assertUniqueMember(groupEntry, accountDn); } - private void assertNoLdapLocGov(PrismObject user, String expLoc, String expOrg) throws ObjectNotFoundException, SchemaException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException { + private void assertNoLdapLocGov(PrismObject user, String expLoc, String expOrg) + throws DirectoryException { UserType userType = user.asObjectable(); - String groupCn = expOrg+":"+expLoc; - String groupDn = "cn="+groupCn+",ou=groups,"+openDJController.getSuffix(); + String groupCn = expOrg + ":" + expLoc; + String groupDn = "cn=" + groupCn + ",ou=groups," + openDJController.getSuffix(); Entry groupEntry = openDJController.fetchAndAssertEntry(groupDn, "groupOfUniqueNames"); display("Group entry", groupEntry); - String accountDn = "uid="+userType.getName()+",ou=people,"+openDJController.getSuffix(); + String accountDn = "uid=" + userType.getName() + ",ou=people," + openDJController.getSuffix(); openDJController.assertNoUniqueMember(groupEntry, accountDn); } - } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapAssociationPerformance.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapAssociationPerformance.java index 5040f9f9ec4..cfc76c1e5bd 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapAssociationPerformance.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapAssociationPerformance.java @@ -28,7 +28,6 @@ import org.testng.annotations.Test; import java.io.File; -import java.io.IOException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.Map; @@ -146,8 +145,6 @@ protected String getLdapResourceOid() { @Test public void test000ClonePerformance() throws SchemaException { - final String TEST_NAME = "test000ClonePerformance"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -164,8 +161,6 @@ public void test000ClonePerformance() throws SchemaException { } @Test public void test010Sanity() throws Exception { - final String TEST_NAME = "test010Sanity"; - Task task = getTestTask(); OperationResult result = task.getResult(); @@ -213,12 +208,12 @@ public void test020GenerateRoles() throws Exception { then(); long endMillis = System.currentTimeMillis(); - recordDuration(TEST_NAME, (endMillis - startMillis)); + recordDuration((endMillis - startMillis)); PerformanceInformation performanceInformation = getRepoPerformanceMonitor() .getThreadLocalPerformanceInformation(); dumpRepoSnapshot("SQL operations for " + TEST_NAME, performanceInformation, "role", NUMBER_OF_GENERATED_ROLES); - dumpGlobalCachePerformanceData(TEST_NAME); + dumpGlobalCachePerformanceData(); result.computeStatus(); assertSuccess(result); @@ -274,11 +269,11 @@ public void test100AddUsers() throws Exception { then(); long endMillis = System.currentTimeMillis(); - recordDuration(TEST_NAME, (endMillis - startMillis)); + recordDuration((endMillis - startMillis)); PerformanceInformation performanceInformation = getRepoPerformanceMonitor().getThreadLocalPerformanceInformation(); - dumpRepoSnapshotPerUser("SQL operations for " + TEST_NAME, performanceInformation); - dumpGlobalCachePerformanceData(TEST_NAME); + dumpRepoSnapshotPerUser(performanceInformation); + dumpGlobalCachePerformanceData(); result.computeStatus(); assertSuccess(result); @@ -286,8 +281,9 @@ public void test100AddUsers() throws Exception { assertLdapConnectorInstances(1); } - private void dumpRepoSnapshotPerUser(String label, PerformanceInformation performanceInformation) { - dumpRepoSnapshot(label, performanceInformation, "user", NUMBER_OF_GENERATED_USERS); + private void dumpRepoSnapshotPerUser(PerformanceInformation performanceInformation) { + dumpRepoSnapshot("SQL operations for " + getTestNameShort(), + performanceInformation, "user", NUMBER_OF_GENERATED_USERS); } private void dumpRepoSnapshot(String label, PerformanceInformation performanceInformation, String unit, int unitCount) { @@ -305,13 +301,8 @@ private void dumpRepoSnapshot(String label, PerformanceInformation performanceIn @Test public void test110RecomputeUsers() throws Exception { - final String TEST_NAME = "test110RecomputeUsers"; - rememberConnectorResourceCounters(); - Task task = getTestTask(); - OperationResult result = task.getResult(); - // WHEN when(); @@ -325,14 +316,13 @@ public void test110RecomputeUsers() throws Exception { // THEN then(); - recordDuration(TEST_NAME,getRunDurationMillis(TASK_RECOMPUTE_1_OID)); - + recordDuration(getRunDurationMillis(TASK_RECOMPUTE_1_OID)); PerformanceInformation performanceInformation = getRepoPerformanceMonitor().getGlobalPerformanceInformation(); - dumpRepoSnapshotPerUser("SQL operations for " + TEST_NAME, performanceInformation); - dumpGlobalCachePerformanceData(TEST_NAME); + dumpRepoSnapshotPerUser(performanceInformation); + dumpGlobalCachePerformanceData(); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_RECOMPUTE_1_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); assertUsers(getNumberOfUsers() + NUMBER_OF_GENERATED_USERS); @@ -369,14 +359,14 @@ public void test120RecomputeUsersNoRoleAndShadowCache() throws Exception { // THEN then(); - recordDuration(TEST_NAME,getRunDurationMillis(TASK_RECOMPUTE_NO_CACHE_OID)); + recordDuration(getRunDurationMillis(TASK_RECOMPUTE_NO_CACHE_OID)); PerformanceInformation performanceInformation = getRepoPerformanceMonitor().getGlobalPerformanceInformation(); - dumpRepoSnapshotPerUser("SQL operations for " + TEST_NAME, performanceInformation); - dumpGlobalCachePerformanceData(TEST_NAME); + dumpRepoSnapshotPerUser(performanceInformation); + dumpGlobalCachePerformanceData(); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_RECOMPUTE_NO_CACHE_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); assertUsers(getNumberOfUsers() + NUMBER_OF_GENERATED_USERS); @@ -415,14 +405,14 @@ public void test130RecomputeUsersMultinode() throws Exception { // THEN then(); - recordDuration(TEST_NAME, getTreeRunDurationMillis(TASK_RECOMPUTE_MULTINODE_OID)); + recordDuration(getTreeRunDurationMillis(TASK_RECOMPUTE_MULTINODE_OID)); PerformanceInformation performanceInformation = getRepoPerformanceMonitor().getGlobalPerformanceInformation(); - dumpRepoSnapshotPerUser("SQL operations for " + TEST_NAME, performanceInformation); - dumpGlobalCachePerformanceData(TEST_NAME); + dumpRepoSnapshotPerUser(performanceInformation); + dumpGlobalCachePerformanceData(); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_RECOMPUTE_MULTINODE_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); assertUsers(getNumberOfUsers() + NUMBER_OF_GENERATED_USERS); @@ -463,15 +453,15 @@ public void test140RecomputeUsersMultinodeMultithreaded() throws Exception { // THEN then(); - recordDuration(TEST_NAME, getTreeRunDurationMillis(TASK_RECOMPUTE_MULTINODE_MULTITHREADED_OID)); + recordDuration(getTreeRunDurationMillis(TASK_RECOMPUTE_MULTINODE_MULTITHREADED_OID)); // todo retrieve this information from finished task PerformanceInformation performanceInformation = getRepoPerformanceMonitor().getGlobalPerformanceInformation(); - dumpRepoSnapshotPerUser("SQL operations for " + TEST_NAME, performanceInformation); - dumpGlobalCachePerformanceData(TEST_NAME); + dumpRepoSnapshotPerUser(performanceInformation); + dumpGlobalCachePerformanceData(); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_RECOMPUTE_MULTINODE_MULTITHREADED_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); assertUsers(getNumberOfUsers() + NUMBER_OF_GENERATED_USERS); @@ -512,15 +502,15 @@ public void test200RecomputeUsersNoDefaultRoleCache() throws Exception { // THEN then(); - recordDuration(TEST_NAME,getRunDurationMillis(TASK_RECOMPUTE_4_OID)); + recordDuration(getRunDurationMillis(TASK_RECOMPUTE_4_OID)); // todo retrieve this information from finished task PerformanceInformation performanceInformation = getRepoPerformanceMonitor().getGlobalPerformanceInformation(); - dumpRepoSnapshotPerUser("SQL operations for " + TEST_NAME, performanceInformation); - dumpGlobalCachePerformanceData(TEST_NAME); + dumpRepoSnapshotPerUser(performanceInformation); + dumpGlobalCachePerformanceData(); OperationStatsType statistics = getTaskTreeOperationStatistics(TASK_RECOMPUTE_4_OID); - displayOperationStatistics("Task operation statistics for " + TEST_NAME, statistics); + displayOperationStatistics(statistics); assertNotNull(statistics); assertUsers(getNumberOfUsers() + NUMBER_OF_GENERATED_USERS); @@ -577,12 +567,8 @@ private void assertSteadyResource() { assertCounterIncrement(InternalCounters.RESOURCE_REPOSITORY_MODIFY_COUNT, 0); } - protected void assertLdapConnectorInstances() throws NumberFormatException, SchemaException, ObjectNotFoundException, CommunicationException, ConfigurationException, ExpressionEvaluationException, IOException, InterruptedException { - assertLdapConnectorInstances(2,4); - } - - private long recordDuration(String label, long duration) { - durations.put(label, duration); + private long recordDuration(long duration) { + durations.put(getTestNameShort(), duration); return duration; } diff --git a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java index b18af1cb09a..49ddbedd183 100644 --- a/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java +++ b/testing/story/src/test/java/com/evolveum/midpoint/testing/story/ldap/TestLdapDependency.java @@ -7,15 +7,10 @@ package com.evolveum.midpoint.testing.story.ldap; +import static org.testng.AssertJUnit.assertNotNull; + +import java.io.File; -import com.evolveum.midpoint.prism.PrismObject; -import com.evolveum.midpoint.schema.constants.MidPointConstants; -import com.evolveum.midpoint.schema.result.OperationResult; -import com.evolveum.midpoint.task.api.Task; -import com.evolveum.midpoint.test.util.TestUtil; -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 org.opends.server.types.DirectoryException; import org.opends.server.types.Entry; import org.springframework.test.annotation.DirtiesContext; @@ -24,32 +19,33 @@ import org.testng.annotations.AfterClass; import org.testng.annotations.Test; -import javax.xml.namespace.QName; -import java.io.File; - -import static org.testng.AssertJUnit.assertNotNull; +import com.evolveum.midpoint.prism.PrismObject; +import com.evolveum.midpoint.schema.result.OperationResult; +import com.evolveum.midpoint.task.api.Task; +import com.evolveum.midpoint.test.ldap.OpenDJController; +import com.evolveum.midpoint.test.util.TestUtil; +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; /** * Testing dependencies: * There are two meta-roles for orgs. * Org Metarole contains two inducements, one for creating organizationalUnit (intent=ou) and one for creating groupOfUniqueNames (intent=group) in ldap. * group depends on ou (since it is created in ou) - * + *

* Org Metarole VIP is very similar it also contains two inducements, one for creating (intent=ou-vip) and one for creating groupOfUniqueNames (intent=group-vip) in ldap. * group-vip depends on ou-cip (since it is created in ou-vip) * * @author michael gruber - * */ -@ContextConfiguration(locations = {"classpath:ctx-story-test-main.xml"}) +@ContextConfiguration(locations = { "classpath:ctx-story-test-main.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_CLASS) -public class TestLdapDependency extends AbstractLdapTest { +public class TestLdapDependency extends AbstractLdapTest { public static final File TEST_DIR = new File(LDAP_TEST_DIR, "dependency"); private static final String RESOURCE_OPENDJ_OID = "10000000-0000-0000-0000-000000000003"; - private static final String RESOURCE_OPENDJ_NAMESPACE = MidPointConstants.NS_RI; - private static final QName OPENDJ_ASSOCIATION_GROUP_NAME = new QName(RESOURCE_OPENDJ_NAMESPACE, "group"); public static final String ORG_TOP_OID = "00000000-8888-6666-0000-100000000001"; @@ -62,7 +58,6 @@ public class TestLdapDependency extends AbstractLdapTest { private static String orgItOid; private static String orgHrOid; - private static final String ORG_TYPE_FUNCTIONAL = "functional"; private static final String LDAP_GROUP_INTENT = "group"; @@ -72,8 +67,6 @@ public class TestLdapDependency extends AbstractLdapTest { private static final String LDAP_OU_INTENT = "ou"; private static final String LDAP_OU_VIP_INTENT = "ou-vip"; - private PrismObject resourceOpenDj; - @Override protected String getLdapResourceOid() { return RESOURCE_OPENDJ_OID; @@ -114,7 +107,7 @@ protected void startResources() throws Exception { } @AfterClass - public static void stopResources() throws Exception { + public static void stopResources() { openDJController.stop(); } @@ -122,9 +115,8 @@ public static void stopResources() throws Exception { public void initSystem(Task initTask, OperationResult initResult) throws Exception { super.initSystem(initTask, initResult); - // Resources - resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, initTask, initResult); + PrismObject resourceOpenDj = importAndGetObjectFromFile(ResourceType.class, getResourceOpenDjFile(), RESOURCE_OPENDJ_OID, initTask, initResult); openDJController.setResource(resourceOpenDj); // Org @@ -138,8 +130,7 @@ public void initSystem(Task initTask, OperationResult initResult) throws Excepti @Test public void test000Sanity() throws Exception { - final String TEST_NAME = "test000Sanity"; - Task task = taskManager.createTaskInstance(TestLdapDependency.class.getName() + "." + TEST_NAME); + Task task = getTestTask(); OperationResult testResultOpenDj = modelService.testResource(RESOURCE_OPENDJ_OID, task); TestUtil.assertSuccess(testResultOpenDj); @@ -150,7 +141,6 @@ public void test000Sanity() throws Exception { @Test public void test100AddOrgIT() throws Exception { - final String TEST_NAME = "test100AddOrgIT"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -177,7 +167,6 @@ public void test100AddOrgIT() throws Exception { @Test public void test150AssignFunctionalRoleToITOrg() throws Exception { - final String TEST_NAME = "test150AssignFunctionalRoleToITOrg"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -206,7 +195,6 @@ public void test150AssignFunctionalRoleToITOrg() throws Exception { @Test public void test170UnassignFunctionalRoleFromITOrg() throws Exception { - final String TEST_NAME = "test170UnassignFunctionalRoleFromITOrg"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -233,10 +221,8 @@ public void test170UnassignFunctionalRoleFromITOrg() throws Exception { //TODO: assert ldap objects deleted... } - @Test public void test200AddOrgHR() throws Exception { - final String TEST_NAME = "test200AddOrgHR"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -263,7 +249,6 @@ public void test200AddOrgHR() throws Exception { @Test public void test250AssignFunctionalAndVipRoleToHROrg() throws Exception { - final String TEST_NAME = "test250AssignFunctionalAndVipRoleToHROrg"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -295,7 +280,6 @@ public void test250AssignFunctionalAndVipRoleToHROrg() throws Exception { @Test public void test270UnassignVipRoleFromHROrg() throws Exception { - final String TEST_NAME = "test270UnassignVipRoleFromHROrg"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -327,7 +311,6 @@ public void test270UnassignVipRoleFromHROrg() throws Exception { //test280AssignVipAndSuperVipRoleToHROrg required for test290UnassignVipRoleFromHROrg @Test public void test280AssignVipAndSuperVipRoleToHROrg() throws Exception { - final String TEST_NAME = "test280AssignVipAndSuperVipRoleToHROrg"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -360,7 +343,6 @@ public void test280AssignVipAndSuperVipRoleToHROrg() throws Exception { @Test public void test290UnassignVipRoleFromHROrg() throws Exception { - final String TEST_NAME = "test290UnassignVipRoleFromHROrg"; Task task = getTestTask(); OperationResult result = task.getResult(); @@ -413,54 +395,36 @@ private PrismObject createOrg(String name, String parentOrgOid) throws return org; } - private void assertLdapObjectsFunctionalOrg(PrismObject org) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { - String orgName = org.getName().toString(); - display("assert org", org.getName()); - - String groupOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, ShadowKindType.ENTITLEMENT, LDAP_GROUP_INTENT); - PrismObject groupShadow = getShadowModel(groupOid); - display("Org "+orgName+" group shadow", groupShadow); - // TODO assert shadow content - - Entry groupEntry = openDJController.searchSingle("cn="+orgName); - assertNotNull("No group LDAP entry for "+orgName, groupEntry); - display("OU GROUP entry", openDJController.toHumanReadableLdifoid(groupEntry)); - openDJController.assertObjectClass(groupEntry, "groupOfUniqueNames"); - - } - - - private void assertLdapObject(PrismObject org, ShadowKindType kind, String intent) throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, ConfigurationException, DirectoryException, ExpressionEvaluationException { - String orgName = org.getName().toString(); + private void assertLdapObject(PrismObject org, ShadowKindType kind, String intent) + throws SchemaException, ObjectNotFoundException, SecurityViolationException, CommunicationException, + ConfigurationException, DirectoryException, ExpressionEvaluationException { + String orgName = org.getName().toString(); display("assert org", orgName); String objOid = getLinkRefOid(org, RESOURCE_OPENDJ_OID, kind, intent); PrismObject objShadow = getShadowModel(objOid); - display("Org "+orgName+" kind " +kind + " intent " + intent +" shadow", objShadow); + display("Org " + orgName + " kind " + kind + " intent " + intent + " shadow", objShadow); // TODO assert shadow content String search = ""; - if (kind.equals(ShadowKindType.ENTITLEMENT)){ - if (LDAP_GROUP_INTENT.equals(intent)) search = "cn="+orgName; - if (LDAP_GROUP_VIP_INTENT.equals(intent)) search = "cn="+orgName+"-vip"; - if (LDAP_GROUP_SUPERVIP_INTENT.equals(intent)) search = "cn="+orgName+"-supervip"; + if (kind.equals(ShadowKindType.ENTITLEMENT)) { + if (LDAP_GROUP_INTENT.equals(intent)) { search = "cn=" + orgName; } + if (LDAP_GROUP_VIP_INTENT.equals(intent)) { search = "cn=" + orgName + "-vip"; } + if (LDAP_GROUP_SUPERVIP_INTENT.equals(intent)) { search = "cn=" + orgName + "-supervip"; } } - if (kind.equals(ShadowKindType.GENERIC)){ - if (LDAP_OU_INTENT.equals(intent)) search = "ou="+orgName; - if (LDAP_OU_VIP_INTENT.equals(intent)) search = "ou="+orgName+"-vip"; + if (kind.equals(ShadowKindType.GENERIC)) { + if (LDAP_OU_INTENT.equals(intent)) { search = "ou=" + orgName; } + if (LDAP_OU_VIP_INTENT.equals(intent)) { search = "ou=" + orgName + "-vip"; } } Entry objEntry = openDJController.searchSingle(search); - assertNotNull("No LDAP entry for "+orgName, objEntry); - display("LDAP entry kind " +kind + " inten " + intent +" ldapObj", objEntry); + assertNotNull("No LDAP entry for " + orgName, objEntry); + display("LDAP entry kind " + kind + " intent " + intent + " ldapObj", objEntry); - if (kind.equals(ShadowKindType.ENTITLEMENT)){ - openDJController.assertObjectClass(objEntry, "groupOfUniqueNames"); + if (kind.equals(ShadowKindType.ENTITLEMENT)) { + OpenDJController.assertObjectClass(objEntry, "groupOfUniqueNames"); } - if (kind.equals(ShadowKindType.GENERIC)){ - openDJController.assertObjectClass(objEntry, "organizationalUnit"); + if (kind.equals(ShadowKindType.GENERIC)) { + OpenDJController.assertObjectClass(objEntry, "organizationalUnit"); } - } - - } From 6f9572188931f3528d8c279515728276191f1bd1 Mon Sep 17 00:00:00 2001 From: Radovan Semancik Date: Tue, 10 Mar 2020 10:20:23 +0100 Subject: [PATCH 53/55] LDAP connector 3.0-M2 --- pom.xml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/pom.xml b/pom.xml index b9064b88a29..b83d517acb6 100644 --- a/pom.xml +++ b/pom.xml @@ -892,7 +892,7 @@ com.evolveum.polygon connector-ldap - 3.0-SNAPSHOT + 3.0-M2 From 1ca953b6168978d116801e455800680e87e0fb2a Mon Sep 17 00:00:00 2001 From: Radovan Semancik Date: Tue, 10 Mar 2020 10:39:05 +0100 Subject: [PATCH 54/55] Post-merge fix --- .../testing/conntest/ad/AbstractAdLdapMultidomainTest.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java index 537362e9d1d..4bd9b09a60d 100644 --- a/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java +++ b/testing/conntest/src/test/java/com/evolveum/midpoint/testing/conntest/ad/AbstractAdLdapMultidomainTest.java @@ -2242,7 +2242,7 @@ public void test901SyncAddAccountHt() throws Exception { protected void assertStepSyncToken(String syncTaskOid, int step, long tsStart, long tsEnd) throws ObjectNotFoundException, SchemaException { OperationResult result = createOperationResult("assertStepSyncToken"); - Task task = taskManager.getTask(syncTaskOid, result); + Task task = taskManager.getTaskPlain(syncTaskOid, result); PrismProperty syncTokenProperty = task.getExtensionPropertyOrClone(SchemaConstants.SYNC_TOKEN); assertNotNull("No sync token", syncTokenProperty); assertNotNull("No sync token value", syncTokenProperty.getRealValue()); From 0be732e4538106556eaf71af18b23a57b30e0680 Mon Sep 17 00:00:00 2001 From: Pavol Mederly Date: Tue, 10 Mar 2020 10:40:06 +0100 Subject: [PATCH 55/55] Do cosmetic changes in task tests (Mainly related to eliminating IDE warnings.) --- .../quartzimpl/AbstractTaskManagerTest.java | 107 +++++++++--------- .../quartzimpl/TestTaskManagerContract.java | 5 +- .../resources/basic/task-001TaskToken.xml | 29 ----- .../resources/basic/task-002OidPresence.xml | 29 ----- .../resources/basic/task-003GetProgress.xml | 9 +- 5 files changed, 57 insertions(+), 122 deletions(-) delete mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-001TaskToken.xml delete mode 100644 repo/task-quartz-impl/src/test/resources/basic/task-002OidPresence.xml diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java index d4b3276ba8f..8c36c44cd55 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/AbstractTaskManagerTest.java @@ -17,6 +17,7 @@ import java.math.BigInteger; import java.util.*; +import org.jetbrains.annotations.NotNull; import org.springframework.beans.factory.annotation.Autowired; import org.testng.annotations.BeforeSuite; import org.xml.sax.SAXException; @@ -45,24 +46,23 @@ import com.evolveum.midpoint.util.exception.SchemaException; import com.evolveum.midpoint.xml.ns._public.common.common_3.*; -public class AbstractTaskManagerTest extends AbstractSpringTest - implements OperationResultTestMixin { - - protected static final String CYCLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-task-handler"; - protected static final String CYCLE_FINISHING_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-finishing-task-handler"; - protected static final String SINGLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/single-task-handler"; - protected static final String SINGLE_TASK_HANDLER_2_URI = "http://midpoint.evolveum.com/test/single-task-handler-2"; - protected static final String SINGLE_TASK_HANDLER_3_URI = "http://midpoint.evolveum.com/test/single-task-handler-3"; - protected static final String SINGLE_WB_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/single-wb-task-handler"; - protected static final String PARTITIONED_WB_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/partitioned-wb-task-handler"; - protected static final String PARTITIONED_WB_TASK_HANDLER_URI_1 = PARTITIONED_WB_TASK_HANDLER_URI + "#1"; - protected static final String PARTITIONED_WB_TASK_HANDLER_URI_2 = PARTITIONED_WB_TASK_HANDLER_URI + "#2"; - protected static final String PARTITIONED_WB_TASK_HANDLER_URI_3 = PARTITIONED_WB_TASK_HANDLER_URI + "#3"; - protected static final String L1_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l1-task-handler"; - protected static final String L2_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l2-task-handler"; - protected static final String L3_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l3-task-handler"; - protected static final String PARALLEL_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/parallel-task-handler"; - protected static final String LONG_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/long-task-handler"; +public class AbstractTaskManagerTest extends AbstractSpringTest implements OperationResultTestMixin { + + private static final String CYCLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-task-handler"; + private static final String CYCLE_FINISHING_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/cycle-finishing-task-handler"; + static final String SINGLE_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/single-task-handler"; + private static final String SINGLE_TASK_HANDLER_2_URI = "http://midpoint.evolveum.com/test/single-task-handler-2"; + private static final String SINGLE_TASK_HANDLER_3_URI = "http://midpoint.evolveum.com/test/single-task-handler-3"; + private static final String SINGLE_WB_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/single-wb-task-handler"; + private static final String PARTITIONED_WB_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/partitioned-wb-task-handler"; + private static final String PARTITIONED_WB_TASK_HANDLER_URI_1 = PARTITIONED_WB_TASK_HANDLER_URI + "#1"; + private static final String PARTITIONED_WB_TASK_HANDLER_URI_2 = PARTITIONED_WB_TASK_HANDLER_URI + "#2"; + private static final String PARTITIONED_WB_TASK_HANDLER_URI_3 = PARTITIONED_WB_TASK_HANDLER_URI + "#3"; + private static final String L1_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l1-task-handler"; + static final String L2_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l2-task-handler"; + static final String L3_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/l3-task-handler"; + private static final String PARALLEL_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/parallel-task-handler"; + private static final String LONG_TASK_HANDLER_URI = "http://midpoint.evolveum.com/test/long-task-handler"; public static final String COMMON_DIR = "src/test/resources/common"; private static final File USER_ADMINISTRATOR_FILE = new File(COMMON_DIR, "user-administrator.xml"); @@ -77,18 +77,16 @@ public class AbstractTaskManagerTest extends AbstractSpringTest @Autowired protected PrismContext prismContext; @Autowired protected SchemaHelper schemaHelper; - protected MockSingleTaskHandler singleHandler1, singleHandler2, singleHandler3; - protected MockWorkBucketsTaskHandler workBucketsTaskHandler; - protected MockWorkBucketsTaskHandler partitionedWorkBucketsTaskHandler; - protected MockSingleTaskHandler l1Handler, l2Handler, l3Handler; - protected MockCycleTaskHandler cycleFinishingHandler; - protected MockParallelTaskHandler parallelTaskHandler; - protected MockLongTaskHandler longTaskHandler; + MockSingleTaskHandler singleHandler1, singleHandler2, singleHandler3; + MockWorkBucketsTaskHandler workBucketsTaskHandler; + MockWorkBucketsTaskHandler partitionedWorkBucketsTaskHandler; + MockSingleTaskHandler l1Handler, l2Handler, l3Handler; + MockParallelTaskHandler parallelTaskHandler; - protected void initHandlers() { - MockCycleTaskHandler cycleHandler = new MockCycleTaskHandler(false); // ordinary recurring task + private void initHandlers() { + MockCycleTaskHandler cycleHandler = new MockCycleTaskHandler(false); // ordinary recurring task taskManager.registerHandler(CYCLE_TASK_HANDLER_URI, cycleHandler); - cycleFinishingHandler = new MockCycleTaskHandler(true); // finishes the handler + MockCycleTaskHandler cycleFinishingHandler = new MockCycleTaskHandler(true); // finishes the handler taskManager.registerHandler(CYCLE_FINISHING_TASK_HANDLER_URI, cycleFinishingHandler); singleHandler1 = new MockSingleTaskHandler("1", taskManager); @@ -118,7 +116,7 @@ protected void initHandlers() { parallelTaskHandler = new MockParallelTaskHandler("1", taskManager); taskManager.registerHandler(PARALLEL_TASK_HANDLER_URI, parallelTaskHandler); - longTaskHandler = new MockLongTaskHandler("1", taskManager); + MockLongTaskHandler longTaskHandler = new MockLongTaskHandler("1", taskManager); taskManager.registerHandler(LONG_TASK_HANDLER_URI, longTaskHandler); } @@ -133,13 +131,8 @@ public void initialize() throws Exception { addObjectFromFile(USER_ADMINISTRATOR_FILE.getPath()); } - protected PrismObject unmarshallJaxbFromFile(String filePath) throws IOException, SchemaException { - File file = new File(filePath); - return PrismTestUtil.parseObject(file); - } - - protected PrismObject addObjectFromFile(String filePath) throws Exception { - PrismObject object = unmarshallJaxbFromFile(filePath); + PrismObject addObjectFromFile(String filePath) throws Exception { + PrismObject object = PrismTestUtil.parseObject(new File(filePath)); OperationResult result = createOperationResult("addObjectFromFile"); try { add(object, result); @@ -147,13 +140,14 @@ protected PrismObject addObjectFromFile(String filePat delete(object, result); add(object, result); } - logger.trace("Object from " + filePath + " added to repository."); + logger.trace("Object from {} added to repository.", filePath); return object; } protected void add(PrismObject object, OperationResult result) throws ObjectAlreadyExistsException, SchemaException { if (object.canRepresent(TaskType.class)) { + //noinspection unchecked,rawtypes taskManager.addTask((PrismObject) object, result); } else { repositoryService.addObject(object, null, result); @@ -168,8 +162,8 @@ protected void delete(PrismObject object, OperationResult } } - protected void waitForTaskClose(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval) throws - CommonException { + void waitForTaskClose(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval) + throws CommonException { waitFor("Waiting for task to close", () -> { Task task = taskManager.getTaskWithResult(taskOid, result); IntegrationTestTools.display("Task while waiting for it to close", task); @@ -177,7 +171,8 @@ protected void waitForTaskClose(String taskOid, OperationResult result, long tim }, timeoutInterval, sleepInterval); } - protected void waitForTaskRunnable(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval) throws + @SuppressWarnings("SameParameterValue") + void waitForTaskRunnable(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval) throws CommonException { waitFor("Waiting for task to become runnable", () -> { Task task = taskManager.getTaskWithResult(taskOid, result); @@ -186,7 +181,8 @@ protected void waitForTaskRunnable(String taskOid, OperationResult result, long }, timeoutInterval, sleepInterval); } - protected void waitForTaskCloseCheckingSubtasks(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval) throws + @SuppressWarnings("SameParameterValue") + void waitForTaskCloseCheckingSubtasks(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval) throws CommonException { waitFor("Waiting for task manager to execute the task", () -> { Task task = taskManager.getTaskWithResult(taskOid, result); @@ -215,7 +211,7 @@ protected void waitForTaskStart(String oid, OperationResult result, long timeout }, timeoutInterval, sleepInterval); } - protected void waitForTaskProgress(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval, + void waitForTaskProgress(String taskOid, OperationResult result, long timeoutInterval, long sleepInterval, int threshold) throws CommonException { waitFor("Waiting for task progress reaching " + threshold, () -> { Task task = taskManager.getTaskWithResult(taskOid, result); @@ -224,11 +220,11 @@ protected void waitForTaskProgress(String taskOid, OperationResult result, long }, timeoutInterval, sleepInterval); } - protected void suspendAndDeleteTasks(String... oids) { + void suspendAndDeleteTasks(String... oids) { taskManager.suspendAndDeleteTasks(Arrays.asList(oids), 20000L, true, new OperationResult("dummy")); } - protected void sleepChecked(long delay) { + void sleepChecked(long delay) { try { Thread.sleep(delay); } catch (InterruptedException e) { @@ -236,7 +232,7 @@ protected void sleepChecked(long delay) { } } - protected void assertTotalSuccessCount(int expectedCount, Collection workers) { + void assertTotalSuccessCount(int expectedCount, Collection workers) { int total = 0; for (Task worker : workers) { total += worker.getStoredOperationStats().getIterativeTaskInformation().getTotalSuccessCount(); @@ -244,11 +240,11 @@ protected void assertTotalSuccessCount(int expectedCount, Collection> retrieveItemsNamed(Object... items) { + Collection> retrieveItemsNamed(Object... items) { return schemaHelper.getOperationOptionsBuilder() .items(items).retrieve() .build(); @@ -349,4 +345,9 @@ protected void display(String title, DebugDumpable value) { protected void display(String title, Object value) { PrismTestUtil.display(title, value); } + + @NotNull + TaskQuartzImpl createTaskFromFile(String filePath, OperationResult result) throws Exception { + return taskManager.createTaskInstance(addObjectFromFile(filePath), result); + } } diff --git a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java index 4f09c3ea90f..dae92dc9872 100644 --- a/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java +++ b/repo/task-quartz-impl/src/test/java/com/evolveum/midpoint/task/quartzimpl/TestTaskManagerContract.java @@ -821,8 +821,7 @@ public void test017WaitForSubtasksEmpty() throws Exception { taskManager.getClusterManager().startClusterManagerThread(); try { - Task rootTask = taskManager.createTaskInstance( - addObjectFromFile(taskFilename()), result); + Task rootTask = createTaskFromFile(taskFilename(), result); display("root task", rootTask); waitForTaskClose(taskOid(), result, 40000, 3000); } finally { @@ -908,7 +907,7 @@ public void test019FinishedHandler() throws Exception { public void test020QueryByExecutionStatus() throws Exception { final OperationResult result = createOperationResult(); - taskManager.createTaskInstance(addObjectFromFile(taskFilename()), result); + addObjectFromFile(taskFilename()); ObjectFilter filter1 = prismContext.queryFor(TaskType.class).item(TaskType.F_EXECUTION_STATUS).eq(TaskExecutionStatusType.WAITING).buildFilter(); ObjectFilter filter2 = prismContext.queryFor(TaskType.class).item(TaskType.F_WAITING_REASON).eq(TaskWaitingReasonType.OTHER).buildFilter(); diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-001TaskToken.xml b/repo/task-quartz-impl/src/test/resources/basic/task-001TaskToken.xml deleted file mode 100644 index a43c6701e01..00000000000 --- a/repo/task-quartz-impl/src/test/resources/basic/task-001TaskToken.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - Passive task 0001 - - 91919190-76e0-59e2-86d6-3d4f02d30001 - - - waiting - - http://midpoint.evolveum.com/test/single-task-handler - - single - diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-002OidPresence.xml b/repo/task-quartz-impl/src/test/resources/basic/task-002OidPresence.xml deleted file mode 100644 index 5aaf20f58e1..00000000000 --- a/repo/task-quartz-impl/src/test/resources/basic/task-002OidPresence.xml +++ /dev/null @@ -1,29 +0,0 @@ - - - - - - - - Passive task 0002 - - 91919190-76e0-59e2-86d6-3d4f02d30002 - - - waiting - - http://midpoint.evolveum.com/test/single-task-handler - - single - diff --git a/repo/task-quartz-impl/src/test/resources/basic/task-003GetProgress.xml b/repo/task-quartz-impl/src/test/resources/basic/task-003GetProgress.xml index 701cc77c153..f9fa71a6fe8 100644 --- a/repo/task-quartz-impl/src/test/resources/basic/task-003GetProgress.xml +++ b/repo/task-quartz-impl/src/test/resources/basic/task-003GetProgress.xml @@ -9,14 +9,7 @@ + xmlns="http://midpoint.evolveum.com/xml/ns/public/common/common-3" xmlns:c="http://midpoint.evolveum.com/xml/ns/public/common/common-3"> Passive task 0003